@trainheroic-unofficial/coach-mcp 3.6.0 → 3.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/server.mjs +330 -143
  2. package/package.json +7 -7
package/dist/server.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { McpServer, acceptedContent, inputRequired, inputResponse } from "@modelcontextprotocol/server";
1
+ import { CLIENT_CAPABILITIES_META_KEY, McpServer, acceptedContent, inputRequired, inputResponse } from "@modelcontextprotocol/server";
2
2
  import { serveStdio } from "@modelcontextprotocol/server/stdio";
3
3
  import process from "node:process";
4
4
  import { z } from "zod";
@@ -414,11 +414,37 @@ const exerciseResolveOutputSchema = z.object({
414
414
  match: exerciseViewSchema.nullable(),
415
415
  candidates: z.array(exerciseViewSchema)
416
416
  });
417
+ /** TrainHeroic's documented exercise parameter-type codes. */
418
+ const exerciseParamTypeSchema = z.union([
419
+ z.literal(0),
420
+ z.literal(1),
421
+ z.literal(2),
422
+ z.literal(3),
423
+ z.literal(4),
424
+ z.literal(5),
425
+ z.literal(6),
426
+ z.literal(7),
427
+ z.literal(10),
428
+ z.literal(11),
429
+ z.literal(12),
430
+ z.literal(13),
431
+ z.literal(14),
432
+ z.literal(18)
433
+ ]);
434
+ const exerciseWriteShape = {
435
+ title: z.string().trim().min(1),
436
+ param_1_type: exerciseParamTypeSchema.optional(),
437
+ param_2_type: exerciseParamTypeSchema.optional()
438
+ };
417
439
  /** Body for creating a custom exercise; extra fields the API accepts are preserved. */
418
440
  const exerciseCreateSchema = z.looseObject({
419
- title: z.string().min(1),
420
- param_1_type: z.number().optional(),
421
- param_2_type: z.number().optional()
441
+ ...exerciseWriteShape,
442
+ points_of_performance: z.string().default("")
443
+ });
444
+ /** Body for updating a custom exercise without clearing fields the caller omitted. */
445
+ const exerciseUpdateSchema = z.looseObject({
446
+ ...exerciseWriteShape,
447
+ points_of_performance: z.string().optional()
422
448
  });
423
449
  //#endregion
424
450
  //#region ../dto/src/messaging.ts
@@ -983,6 +1009,15 @@ async function apiCall(ctx, method, path, options, hint) {
983
1009
  const NOT_CONFIRMED = "Not confirmed — the user declined. Nothing was changed.";
984
1010
  /** Appended to the prompt so the fallback survives whichever way a client surfaces the request. */
985
1011
  const FALLBACK_HINT = " (If you cannot show this prompt, re-run the tool with confirm:true once the user has agreed.)";
1012
+ const CONFIRMATION_REQUIRED = "Ask the user to approve this action, then retry the tool with confirm:true only after they agree. Nothing was changed.";
1013
+ /** `undefined` means a legacy request, whose capability check belongs to the SDK's shim. */
1014
+ function modernClientSupportsFormElicitation(ctx) {
1015
+ const envelope = ctx.mcpReq.envelope;
1016
+ if (envelope === void 0) return void 0;
1017
+ const elicitation = envelope[CLIENT_CAPABILITIES_META_KEY]?.elicitation;
1018
+ if (elicitation === void 0) return false;
1019
+ return elicitation.form !== void 0 || elicitation.url === void 0;
1020
+ }
986
1021
  /**
987
1022
  * Confirm a destructive/athlete-facing action.
988
1023
  *
@@ -998,14 +1033,15 @@ const FALLBACK_HINT = " (If you cannot show this prompt, re-run the tool with co
998
1033
  * confirmation message ever needs data fetched first, that fetch must be idempotent.
999
1034
  *
1000
1035
  * Written once in the 2026 `inputRequired` style: modern clients retry with `inputResponses`.
1001
- * A client that cannot elicit at all never reaches the denial below — the SDK rejects the
1002
- * request before the retry — so it must pass `confirm: true`, which is why the hint rides inside
1003
- * the prompt text itself.
1036
+ * MCP correctly rejects unsupported embedded requests with `-32021`. This application has an
1037
+ * alternate `confirm: true` flow, so a modern client that does not declare form elicitation gets
1038
+ * a model-readable tool error that tells it how to recover while the gate remains closed.
1004
1039
  */
1005
1040
  function confirmGate(ctx, message, confirmArg) {
1006
1041
  if (confirmArg === true) return void 0;
1007
1042
  if (acceptedContent(ctx.mcpReq.inputResponses, "confirm")?.confirm === true) return void 0;
1008
1043
  if (inputResponse(ctx.mcpReq.inputResponses, "confirm").kind !== "missing") return errorResult(NOT_CONFIRMED);
1044
+ if (modernClientSupportsFormElicitation(ctx) === false) return errorResult(`${message} ${CONFIRMATION_REQUIRED}`);
1009
1045
  const prompt = message + FALLBACK_HINT;
1010
1046
  return inputRequired({ inputRequests: { confirm: inputRequired.elicit({
1011
1047
  message: prompt,
@@ -1032,12 +1068,47 @@ function confirmGate(ctx, message, confirmArg) {
1032
1068
  */
1033
1069
  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.";
1034
1070
  //#endregion
1071
+ //#region ../js/src/date-window.ts
1072
+ const DAY_MS = 864e5;
1073
+ const ISO_DAY = /^\d{4}-\d{2}-\d{2}$/u;
1074
+ const MAX_DATE_WINDOWS = 100;
1075
+ function dayNumber(value) {
1076
+ if (!ISO_DAY.test(value)) return null;
1077
+ const timestamp = Date.parse(`${value}T00:00:00Z`);
1078
+ if (!Number.isFinite(timestamp) || new Date(timestamp).toISOString().slice(0, 10) !== value) return null;
1079
+ return timestamp / DAY_MS;
1080
+ }
1081
+ function isoDay$1(day) {
1082
+ return (/* @__PURE__ */ new Date(day * DAY_MS)).toISOString().slice(0, 10);
1083
+ }
1084
+ /** Number of calendar days in an inclusive ISO-date range, or null for an invalid range. */
1085
+ function dateSpanDays(start, end) {
1086
+ const first = dayNumber(start);
1087
+ const last = dayNumber(end);
1088
+ return first === null || last === null || first > last ? null : last - first + 1;
1089
+ }
1090
+ /** Split an inclusive ISO-date range into at most 100 ordered, non-overlapping windows. */
1091
+ function splitDateRange(start, end, maxDays) {
1092
+ const first = dayNumber(start);
1093
+ const last = dayNumber(end);
1094
+ if (first === null || last === null || first > last) return null;
1095
+ if (!Number.isSafeInteger(maxDays) || maxDays < 1) throw new RangeError("maxDays must be a positive integer.");
1096
+ if (Math.ceil((last - first + 1) / maxDays) > MAX_DATE_WINDOWS) throw new RangeError(`Date range is limited to ${MAX_DATE_WINDOWS} windows; narrow the range or increase the window size.`);
1097
+ const windows = [];
1098
+ for (let cursor = first; cursor <= last; cursor += maxDays) windows.push({
1099
+ start: isoDay$1(cursor),
1100
+ end: isoDay$1(Math.min(cursor + maxDays - 1, last))
1101
+ });
1102
+ return windows;
1103
+ }
1104
+ //#endregion
1035
1105
  //#region ../js/src/http-error.ts
1036
1106
  const MAX_REQUEST_KEYS = 50;
1037
1107
  const MAX_RESPONSE_DEPTH = 4;
1038
1108
  const MAX_RESPONSE_KEYS = 20;
1039
1109
  const MAX_RESPONSE_ITEMS = 10;
1040
1110
  const MAX_RESPONSE_NODES = 50;
1111
+ const MAX_RESPONSE_STRING = 2e3;
1041
1112
  const RESPONSE_DIAGNOSTIC_KEYS = /* @__PURE__ */ new Set([
1042
1113
  "code",
1043
1114
  "detail",
@@ -1075,6 +1146,11 @@ const PARAMETER_TYPES = /* @__PURE__ */ new Set([
1075
1146
  14,
1076
1147
  18
1077
1148
  ]);
1149
+ /** Keep provider diagnostics useful while removing common credentials and direct identifiers. */
1150
+ function redactText(value) {
1151
+ const redacted = value.slice(0, MAX_RESPONSE_STRING).replace(/\bAuthorization(["']?\s*[:=]\s*)(?:"(?:\\(?:[\s\S]|$)|[^"\\])*(?:"|$)|'(?:\\(?:[\s\S]|$)|[^'\\])*(?:'|$)|[^"'\r\n,;&]+)/giu, (_match, separator) => `Authorization${separator}[Redacted]`).replace(/\bBearer\s+[A-Za-z0-9._~+/-]+=*/giu, "Bearer [Redacted]").replace(/\b(password|passwd|secret|token|access[_-]?token|refresh[_-]?token|session(?:[_-]?(?:id|token))?|api[_-]?key|client[_-]?secret)(["']?\s*[:=]\s*)(?:"(?:\\(?:[\s\S]|$)|[^"\\])*(?:"|$)|'(?:\\(?:[\s\S]|$)|[^'\\])*(?:'|$)|[^"'\r\n,;&}\]]+)/giu, (_match, key, separator) => `${key}${separator}[Redacted]`).replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/giu, "[Redacted email]").replace(/\b(?:\d{1,3}\.){3}\d{1,3}\b/gu, "[Redacted IP]").replace(/\b\d{3}-\d{2}-\d{4}\b/gu, "[Redacted]").replace(/\b(?:bearer\s+)?[a-f0-9]{32,}\b/giu, "[Redacted]");
1152
+ return value.length <= MAX_RESPONSE_STRING ? redacted : `${redacted}…[truncated]`;
1153
+ }
1078
1154
  function safeFieldName(key) {
1079
1155
  if (key === "__proto__" || key === "constructor" || key === "prototype") return "[Redacted key]";
1080
1156
  if (!/^[A-Za-z_][A-Za-z0-9_.-]{0,79}$/.test(key)) return "[Redacted key]";
@@ -1102,17 +1178,22 @@ function requestBodySummary(body) {
1102
1178
  const entries = boundedEntries(body, MAX_REQUEST_KEYS).sort(([left], [right]) => left.localeCompare(right));
1103
1179
  const keys = entries.map(([key]) => safeFieldName(key));
1104
1180
  const values = {};
1181
+ const arrayLengths = {};
1105
1182
  for (const [key, value] of entries) {
1106
1183
  const safeValue = safeRequestValue(key, value);
1107
1184
  if (safeValue !== void 0) values[safeFieldName(key)] = safeValue;
1185
+ if (Array.isArray(value)) arrayLengths[safeFieldName(key)] = value.length;
1108
1186
  }
1109
- return Object.keys(values).length > 0 ? {
1187
+ const byKey = new Map(entries);
1188
+ const dateStart = byKey.get("date_start");
1189
+ const dateEnd = byKey.get("date_end");
1190
+ const span = typeof dateStart === "string" && typeof dateEnd === "string" ? dateSpanDays(dateStart, dateEnd) : null;
1191
+ return {
1110
1192
  type: "object",
1111
1193
  keys,
1112
- values
1113
- } : {
1114
- type: "object",
1115
- keys
1194
+ ...Object.keys(values).length > 0 ? { values } : {},
1195
+ ...Object.keys(arrayLengths).length > 0 ? { arrayLengths } : {},
1196
+ ...span === null ? {} : { dateSpanDays: span }
1116
1197
  };
1117
1198
  }
1118
1199
  const primitive = typeof body;
@@ -1124,7 +1205,7 @@ function sanitizedDiagnosticValue(value, depth, budget, field) {
1124
1205
  if (value === null) return null;
1125
1206
  if (typeof value === "boolean") return field && RESPONSE_BOOLEAN_KEYS.has(field) ? value : "[Redacted]";
1126
1207
  if (typeof value === "number") return field && RESPONSE_STATUS_KEYS.has(field) && Number.isInteger(value) && value >= 100 && value <= 599 ? value : "[Redacted]";
1127
- if (typeof value === "string") return "[Redacted]";
1208
+ if (typeof value === "string") return redactText(value);
1128
1209
  if (depth >= MAX_RESPONSE_DEPTH) return "[Truncated]";
1129
1210
  if (Array.isArray(value)) {
1130
1211
  const result = [];
@@ -1203,6 +1284,12 @@ function safeResponseBodyDiagnostics(body) {
1203
1284
  return "[Unavailable]";
1204
1285
  }
1205
1286
  }
1287
+ /** Format a bounded provider diagnostic for an in-band tool or SDK error. */
1288
+ function trainHeroicApiErrorMessage(label, status, responseBody) {
1289
+ const diagnostic = safeResponseBodyDiagnostics(responseBody);
1290
+ const detail = diagnostic && typeof diagnostic === "object" && !Array.isArray(diagnostic) ? typeof diagnostic.message === "string" ? diagnostic.message : JSON.stringify(diagnostic) : typeof diagnostic === "string" ? diagnostic : JSON.stringify(diagnostic);
1291
+ return detail && detail !== "{\"type\":\"object\"}" ? `${label} failed (HTTP ${status}): ${detail}` : `${label} failed (HTTP ${status}).`;
1292
+ }
1206
1293
  /** A final non-2xx response plus bounded, telemetry-safe request and response diagnostics. */
1207
1294
  var TrainHeroicHttpError = class extends Error {
1208
1295
  name = "TrainHeroicHttpError";
@@ -1230,6 +1317,9 @@ function notifyHttpError(handler, method, url, status, diagnostics = {}) {
1230
1317
  } catch {}
1231
1318
  }
1232
1319
  //#endregion
1320
+ //#region ../js/src/transport.ts
1321
+ const defaultTrainHeroicTransport = (url, init) => fetch(url, init);
1322
+ //#endregion
1233
1323
  //#region ../js/src/auth.ts
1234
1324
  const DEFAULT_AUTH_URL = "https://apis.trainheroic.com/auth";
1235
1325
  /**
@@ -1253,7 +1343,7 @@ function authUrl() {
1253
1343
  */
1254
1344
  async function loginTrainHeroic(email, password, options = {}) {
1255
1345
  const url = authUrl();
1256
- const res = await fetch(url, {
1346
+ const res = await (options.transport ?? defaultTrainHeroicTransport)(url, {
1257
1347
  method: "POST",
1258
1348
  headers: {
1259
1349
  "content-type": "application/x-www-form-urlencoded",
@@ -1265,6 +1355,7 @@ async function loginTrainHeroic(email, password, options = {}) {
1265
1355
  }).toString()
1266
1356
  });
1267
1357
  if (!res.ok) {
1358
+ await res.body?.cancel().catch(() => {});
1268
1359
  notifyHttpError(options.onHttpError, "POST", url, res.status);
1269
1360
  return null;
1270
1361
  }
@@ -1278,127 +1369,40 @@ async function loginTrainHeroic(email, password, options = {}) {
1278
1369
  };
1279
1370
  }
1280
1371
  //#endregion
1281
- //#region ../js/src/client.ts
1282
- const DEFAULT_COACH_BASE = "https://api.trainheroic.com";
1283
- const DEFAULT_APIS_BASE = "https://apis.trainheroic.com";
1372
+ //#region ../../node_modules/.pnpm/es-toolkit@1.52.0/node_modules/es-toolkit/dist/array/chunk.mjs
1284
1373
  /**
1285
- * Resolve an API host, allowing an env override. The override exists so a test harness can point
1286
- * the client at a local fake backend (and it doubles as a staging knob); production leaves these
1287
- * unset and gets the real hosts. Read through `globalThis.process?.env` — not an `import process`
1288
- * — so the runtime-agnostic `.` entry stays free of `node:*` and runs unchanged on workerd, and
1289
- * read per request (not at module load) so a value the harness sets in the child env always wins.
1290
- */
1291
- function envBase(key, fallback) {
1292
- const v = (globalThis.process?.env)?.[key];
1293
- return v && v.length > 0 ? v : fallback;
1294
- }
1295
- var TrainHeroicAuthError = class extends Error {
1296
- name = "TrainHeroicAuthError";
1297
- };
1298
- /**
1299
- * Authenticated TrainHeroic API client. Holds the credentials (on the hosted Worker, from the
1300
- * grant's encrypted props) and a lazily-acquired session token cached in memory for the life of
1301
- * *this client instance* — nothing longer. On a 401/403 it re-logs in once and retries, since
1302
- * TrainHeroic has no refresh token and sessions expire after ~1-2h.
1374
+ * Splits an array into smaller arrays of a specified length.
1303
1375
  *
1304
- * Anything that wants a session to outlive one client owns that itself: pass a previously
1305
- * acquired token as `sessionId` and keep the new one via `options.onSession`. That matters
1306
- * wherever clients are short-lived — the hosted Worker builds one per HTTP request, and each CLI
1307
- * invocation is a fresh process — because otherwise every operation replays the password.
1376
+ * This function takes an input array and divides it into multiple smaller arrays,
1377
+ * each of a specified length. If the input array cannot be evenly divided,
1378
+ * the final sub-array will contain the remaining elements.
1379
+ *
1380
+ * @template T The type of elements in the array.
1381
+ * @param arr - The array to be chunked into smaller arrays.
1382
+ * @param size - The size of each smaller array. Must be a positive integer.
1383
+ * @returns A two-dimensional array where each sub-array has a maximum length of `size`.
1384
+ * @throws {Error} Throws an error if `size` is not a positive integer.
1385
+ *
1386
+ * @example
1387
+ * // Splits an array of numbers into sub-arrays of length 2
1388
+ * chunk([1, 2, 3, 4, 5], 2);
1389
+ * // Returns: [[1, 2], [3, 4], [5]]
1390
+ *
1391
+ * @example
1392
+ * // Splits an array of strings into sub-arrays of length 3
1393
+ * chunk(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 3);
1394
+ * // Returns: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]
1308
1395
  */
1309
- var TrainHeroicClient = class {
1310
- #email;
1311
- #password;
1312
- #onSession;
1313
- #onHttpError;
1314
- #sessionId;
1315
- #loginInFlight = null;
1316
- constructor(email, password, sessionId = null, options = {}) {
1317
- this.#email = email;
1318
- this.#password = password;
1319
- this.#sessionId = sessionId;
1320
- this.#onSession = options.onSession;
1321
- this.#onHttpError = options.onHttpError;
1322
- }
1323
- get sessionId() {
1324
- return this.#sessionId;
1325
- }
1326
- async #ensureSession() {
1327
- if (this.#sessionId) return this.#sessionId;
1328
- this.#loginInFlight ??= this.#login();
1329
- try {
1330
- return await this.#loginInFlight;
1331
- } finally {
1332
- this.#loginInFlight = null;
1333
- }
1396
+ function chunk(arr, size) {
1397
+ if (!Number.isInteger(size) || size <= 0) throw new Error("Size must be an integer greater than zero.");
1398
+ const chunkLength = Math.ceil(arr.length / size);
1399
+ const result = Array(chunkLength);
1400
+ for (let index = 0; index < chunkLength; index++) {
1401
+ const start = index * size;
1402
+ const end = start + size;
1403
+ result[index] = arr.slice(start, end);
1334
1404
  }
1335
- async #login() {
1336
- const session = await loginTrainHeroic(this.#email, this.#password, this.#onHttpError ? { onHttpError: this.#onHttpError } : {});
1337
- if (!session) throw new TrainHeroicAuthError("TrainHeroic login failed");
1338
- this.#sessionId = session.sessionId;
1339
- try {
1340
- this.#onSession?.(this.#sessionId);
1341
- } catch {}
1342
- return this.#sessionId;
1343
- }
1344
- async request(method, path, options = {}) {
1345
- const url = `${options.base === "apis" ? envBase("TH_APIS_BASE", DEFAULT_APIS_BASE) : envBase("TH_COACH_BASE", DEFAULT_COACH_BASE)}/${path.replace(/^\//, "")}`;
1346
- let session = await this.#ensureSession();
1347
- let res = await this.#send(method, url, session, options.body);
1348
- if (res.status === 401 || res.status === 403) {
1349
- if (this.#sessionId === session) this.#sessionId = null;
1350
- session = await this.#ensureSession();
1351
- res = await this.#send(method, url, session, options.body);
1352
- }
1353
- const shouldReport = !res.ok && !options.expectedStatuses?.includes(res.status);
1354
- let text;
1355
- try {
1356
- text = await res.text();
1357
- } catch (error) {
1358
- if (shouldReport) notifyHttpError(this.#onHttpError, method, url, res.status, { requestBody: options.body });
1359
- throw error;
1360
- }
1361
- const data = parseResponseText(text);
1362
- if (shouldReport) notifyHttpError(this.#onHttpError, method, url, res.status, {
1363
- requestBody: options.body,
1364
- responseBody: data
1365
- });
1366
- return {
1367
- status: res.status,
1368
- ok: res.ok,
1369
- data
1370
- };
1371
- }
1372
- #send(method, url, session, body) {
1373
- const upper = method.toUpperCase();
1374
- const headers = {
1375
- accept: "application/json",
1376
- "session-token": session
1377
- };
1378
- const init = {
1379
- method: upper,
1380
- headers
1381
- };
1382
- if (body !== void 0 && upper !== "GET" && upper !== "DELETE") {
1383
- headers["content-type"] = "application/json";
1384
- init.body = JSON.stringify(body);
1385
- }
1386
- return fetch(url, init);
1387
- }
1388
- };
1389
- //#endregion
1390
- //#region ../js/src/response-check.ts
1391
- /**
1392
- * Validate an API response against its (loose) expected shape and warn once on drift.
1393
- * Never throws: callers keep working via defensive coercion. This only surfaces a signal
1394
- * when TrainHeroic renames or drops a field we read.
1395
- */
1396
- function checkResponse(schema, data, label) {
1397
- const result = schema.safeParse(data);
1398
- if (result.success) return;
1399
- const issue = result.error.issues[0];
1400
- const where = issue && issue.path.length > 0 ? issue.path.join(".") : "(root)";
1401
- console.warn(`[trainheroic] response drift in ${label} at ${where}: ${issue?.message ?? "shape mismatch"}`);
1405
+ return result;
1402
1406
  }
1403
1407
  //#endregion
1404
1408
  //#region ../../node_modules/.pnpm/es-toolkit@1.52.0/node_modules/es-toolkit/dist/array/uniq.mjs
@@ -1657,6 +1661,141 @@ function assertPositiveInteger(value, label) {
1657
1661
  if (!Number.isInteger(value) || value < 1) throw new RangeError(`${label} must be a positive integer; received ${value}.`);
1658
1662
  }
1659
1663
  //#endregion
1664
+ //#region ../js/src/client.ts
1665
+ const DEFAULT_COACH_BASE = "https://api.trainheroic.com";
1666
+ const DEFAULT_APIS_BASE = "https://apis.trainheroic.com";
1667
+ const MAX_REQUEST_CONCURRENCY = 4;
1668
+ /**
1669
+ * Resolve an API host, allowing an env override. The override exists so a test harness can point
1670
+ * the client at a local fake backend (and it doubles as a staging knob); production leaves these
1671
+ * unset and gets the real hosts. Read through `globalThis.process?.env` — not an `import process`
1672
+ * — so the runtime-agnostic `.` entry stays free of `node:*` and runs unchanged on workerd, and
1673
+ * read per request (not at module load) so a value the harness sets in the child env always wins.
1674
+ */
1675
+ function envBase(key, fallback) {
1676
+ const v = (globalThis.process?.env)?.[key];
1677
+ return v && v.length > 0 ? v : fallback;
1678
+ }
1679
+ var TrainHeroicAuthError = class extends Error {
1680
+ name = "TrainHeroicAuthError";
1681
+ };
1682
+ /**
1683
+ * Authenticated TrainHeroic API client. Holds the credentials (on the hosted Worker, from the
1684
+ * grant's encrypted props) and a lazily-acquired session token cached in memory for the life of
1685
+ * *this client instance* — nothing longer. On a 401/403 it re-logs in once and retries, since
1686
+ * TrainHeroic has no refresh token and sessions expire after ~1-2h.
1687
+ *
1688
+ * Anything that wants a session to outlive one client owns that itself: pass a previously
1689
+ * acquired token as `sessionId` and keep the new one via `options.onSession`. That matters
1690
+ * wherever clients are short-lived — the hosted Worker builds one per HTTP request, and each CLI
1691
+ * invocation is a fresh process — because otherwise every operation replays the password.
1692
+ */
1693
+ var TrainHeroicClient = class {
1694
+ #email;
1695
+ #password;
1696
+ #onSession;
1697
+ #onHttpError;
1698
+ #transport;
1699
+ #requestLimit = createLimiter(MAX_REQUEST_CONCURRENCY);
1700
+ #sessionId;
1701
+ #loginInFlight = null;
1702
+ constructor(email, password, sessionId = null, options = {}) {
1703
+ this.#email = email;
1704
+ this.#password = password;
1705
+ this.#sessionId = sessionId;
1706
+ this.#onSession = options.onSession;
1707
+ this.#onHttpError = options.onHttpError;
1708
+ this.#transport = options.transport ?? defaultTrainHeroicTransport;
1709
+ }
1710
+ get sessionId() {
1711
+ return this.#sessionId;
1712
+ }
1713
+ async #ensureSession() {
1714
+ if (this.#sessionId) return this.#sessionId;
1715
+ this.#loginInFlight ??= this.#login();
1716
+ try {
1717
+ return await this.#loginInFlight;
1718
+ } finally {
1719
+ this.#loginInFlight = null;
1720
+ }
1721
+ }
1722
+ async #login() {
1723
+ const session = await loginTrainHeroic(this.#email, this.#password, {
1724
+ ...this.#onHttpError ? { onHttpError: this.#onHttpError } : {},
1725
+ transport: this.#transport
1726
+ });
1727
+ if (!session) throw new TrainHeroicAuthError("TrainHeroic login failed");
1728
+ this.#sessionId = session.sessionId;
1729
+ try {
1730
+ this.#onSession?.(this.#sessionId);
1731
+ } catch {}
1732
+ return this.#sessionId;
1733
+ }
1734
+ async request(method, path, options = {}) {
1735
+ await this.#ensureSession();
1736
+ return this.#requestLimit.run(() => this.#request(method, path, options));
1737
+ }
1738
+ async #request(method, path, options) {
1739
+ const url = `${options.base === "apis" ? envBase("TH_APIS_BASE", DEFAULT_APIS_BASE) : envBase("TH_COACH_BASE", DEFAULT_COACH_BASE)}/${path.replace(/^\//, "")}`;
1740
+ let session = await this.#ensureSession();
1741
+ let res = await this.#send(method, url, session, options.body);
1742
+ if (res.status === 401 || res.status === 403) {
1743
+ await res.body?.cancel().catch(() => {});
1744
+ if (this.#sessionId === session) this.#sessionId = null;
1745
+ session = await this.#ensureSession();
1746
+ res = await this.#send(method, url, session, options.body);
1747
+ }
1748
+ const shouldReport = !res.ok && !options.expectedStatuses?.includes(res.status);
1749
+ let text;
1750
+ try {
1751
+ text = await res.text();
1752
+ } catch (error) {
1753
+ if (shouldReport) notifyHttpError(this.#onHttpError, method, url, res.status, { requestBody: options.body });
1754
+ throw error;
1755
+ }
1756
+ const data = parseResponseText(text);
1757
+ if (shouldReport) notifyHttpError(this.#onHttpError, method, url, res.status, {
1758
+ requestBody: options.body,
1759
+ responseBody: data
1760
+ });
1761
+ return {
1762
+ status: res.status,
1763
+ ok: res.ok,
1764
+ data
1765
+ };
1766
+ }
1767
+ #send(method, url, session, body) {
1768
+ const upper = method.toUpperCase();
1769
+ const headers = {
1770
+ accept: "application/json",
1771
+ "session-token": session
1772
+ };
1773
+ const init = {
1774
+ method: upper,
1775
+ headers
1776
+ };
1777
+ if (body !== void 0 && upper !== "GET" && upper !== "DELETE") {
1778
+ headers["content-type"] = "application/json";
1779
+ init.body = JSON.stringify(body);
1780
+ }
1781
+ return this.#transport(url, init);
1782
+ }
1783
+ };
1784
+ //#endregion
1785
+ //#region ../js/src/response-check.ts
1786
+ /**
1787
+ * Validate an API response against its (loose) expected shape and warn once on drift.
1788
+ * Never throws: callers keep working via defensive coercion. This only surfaces a signal
1789
+ * when TrainHeroic renames or drops a field we read.
1790
+ */
1791
+ function checkResponse(schema, data, label) {
1792
+ const result = schema.safeParse(data);
1793
+ if (result.success) return;
1794
+ const issue = result.error.issues[0];
1795
+ const where = issue && issue.path.length > 0 ? issue.path.join(".") : "(root)";
1796
+ console.warn(`[trainheroic] response drift in ${label} at ${where}: ${issue?.message ?? "shape mismatch"}`);
1797
+ }
1798
+ //#endregion
1660
1799
  //#region ../js/src/athlete.ts
1661
1800
  async function getJson(client, path, label) {
1662
1801
  const res = await client.request("GET", path);
@@ -3341,12 +3480,15 @@ const ANALYTICS_BODY_KEY = {
3341
3480
  exerciseId: "exercise_id",
3342
3481
  useMetric: "use_metric"
3343
3482
  };
3483
+ const TRAINING_SUMMARY_USER_BATCH = 5;
3484
+ const TRAINING_SUMMARY_RANGE_DAYS = 90;
3485
+ const MAX_TRAINING_SUMMARY_REQUESTS = 100;
3344
3486
  /**
3345
3487
  * Build the request body for an analytics metric and POST it. Team metrics need `teamId`;
3346
3488
  * athlete metrics need one or more `userIds` (passed together — the report returns a row per
3347
3489
  * athlete). Throws a readable Error when a required input is missing or the call fails.
3348
3490
  */
3349
- async function queryAnalytics(client, args) {
3491
+ async function requestAnalytics(client, args) {
3350
3492
  const spec = ANALYTICS_METRICS[args.metric];
3351
3493
  const body = {};
3352
3494
  if (spec.scope === "team") {
@@ -3374,6 +3516,42 @@ async function queryAnalytics(client, args) {
3374
3516
  if (!res.ok) throw new Error(`Analytics ${args.metric} failed (HTTP ${res.status}).`);
3375
3517
  return res.data;
3376
3518
  }
3519
+ function reportRows(report) {
3520
+ if (report === null || typeof report !== "object") return null;
3521
+ const rows = report.rows;
3522
+ return Array.isArray(rows) ? rows : null;
3523
+ }
3524
+ /**
3525
+ * Query one analytics metric. Large training-summary reads are serialized as small user/date
3526
+ * batches because that endpoint otherwise spends roughly a minute building one oversized report
3527
+ * before its gateway returns 504. Rejects plans above 100 total requests.
3528
+ */
3529
+ async function queryAnalytics(client, args) {
3530
+ if (args.metric !== "training-summary-athlete" || args.userIds === void 0 || args.userIds.length === 0 || args.dateStart === void 0 || args.dateEnd === void 0) return requestAnalytics(client, args);
3531
+ const windows = splitDateRange(args.dateStart, args.dateEnd, TRAINING_SUMMARY_RANGE_DAYS);
3532
+ if (windows === null) return requestAnalytics(client, args);
3533
+ const uniqueUserIds = [...new Set(args.userIds)];
3534
+ if (Math.ceil(uniqueUserIds.length / TRAINING_SUMMARY_USER_BATCH) * windows.length > MAX_TRAINING_SUMMARY_REQUESTS) throw new RangeError(`Training summary is limited to ${MAX_TRAINING_SUMMARY_REQUESTS} batched requests; narrow the date range or pass fewer athletes.`);
3535
+ const requests = chunk(uniqueUserIds, TRAINING_SUMMARY_USER_BATCH).flatMap((userIds) => windows.map((window) => ({
3536
+ ...args,
3537
+ userIds,
3538
+ dateStart: window.start,
3539
+ dateEnd: window.end
3540
+ })));
3541
+ if (requests.length === 1) return requestAnalytics(client, requests[0]);
3542
+ let merged = null;
3543
+ for (const request of requests) {
3544
+ const report = await requestAnalytics(client, request);
3545
+ const rows = reportRows(report);
3546
+ if (rows === null) throw new Error("Training summary returned an unexpected batched report shape.");
3547
+ if (merged === null) merged = {
3548
+ ...report,
3549
+ rows: [...rows]
3550
+ };
3551
+ else merged.rows.push(...rows);
3552
+ }
3553
+ return merged;
3554
+ }
3377
3555
  /**
3378
3556
  * Resolve a team's roster to athlete user ids. `/v5/athletes` is the org-wide roster and the only
3379
3557
  * place per-team membership lives (each row's `groups` holds the team/group ids it belongs to);
@@ -3401,9 +3579,9 @@ function toNum(v) {
3401
3579
  }
3402
3580
  /**
3403
3581
  * Team-wide training volume over an inclusive date window. The `training-summary-athlete`
3404
- * analytics report already returns the team in one call — one row per logged session across all
3405
- * `athleteIds` — so this fans nothing out: it queries once, groups rows by athlete (summing
3406
- * volume/reps and counting sessions), and rolls the athletes up into a team total. Athletes who
3582
+ * analytics report returns one row per logged session across all `athleteIds`; `queryAnalytics`
3583
+ * splits oversized requests and merges those rows before this function groups them by athlete,
3584
+ * sums volume/reps, counts sessions, and rolls the athletes up into a team total. Athletes who
3407
3585
  * logged nothing in range simply have no rows and are omitted. The windowed counterpart to the
3408
3586
  * all-time `fetchRosterActivity` snapshot, which has no date range.
3409
3587
  */
@@ -3527,6 +3705,7 @@ function classifyMainLift(title) {
3527
3705
  return null;
3528
3706
  }
3529
3707
  const DEFAULT_MONTHS = 12;
3708
+ const WORKOUT_RANGE_DAYS = 180;
3530
3709
  function pad2(n) {
3531
3710
  return String(n).padStart(2, "0");
3532
3711
  }
@@ -3544,12 +3723,18 @@ function isoDay(d) {
3544
3723
  */
3545
3724
  async function resolveAthleteMainLifts(client, athleteId, opts = {}) {
3546
3725
  const months = opts.months ?? DEFAULT_MONTHS;
3726
+ if (!Number.isSafeInteger(months) || months < 1) throw new RangeError("months must be a positive integer.");
3547
3727
  const now = opts.now ?? /* @__PURE__ */ new Date();
3548
- const start = new Date(now.getFullYear(), now.getMonth() - (months - 1), 1);
3728
+ const startDay = isoDay(new Date(now.getFullYear(), now.getMonth() - (months - 1), 1));
3729
+ const endDay = isoDay(now);
3730
+ const windows = splitDateRange(startDay, endDay, WORKOUT_RANGE_DAYS) ?? [{
3731
+ start: startDay,
3732
+ end: endDay
3733
+ }];
3549
3734
  const tally = /* @__PURE__ */ new Map();
3550
3735
  let workouts = [];
3551
3736
  try {
3552
- workouts = await fetchCoachAthleteWorkouts(client, athleteId, isoDay(start), isoDay(now));
3737
+ for (const window of windows) workouts.push(...await fetchCoachAthleteWorkouts(client, athleteId, window.start, window.end));
3553
3738
  } catch {
3554
3739
  workouts = [];
3555
3740
  }
@@ -3892,7 +4077,9 @@ var ExerciseLibrary = class {
3892
4077
  };
3893
4078
  }
3894
4079
  async create(body) {
3895
- return this.#writeThrough(CREATE_PATH, body, "create");
4080
+ const requestBody = { ...body };
4081
+ if (requestBody.points_of_performance === void 0) requestBody.points_of_performance = "";
4082
+ return this.#writeThrough(CREATE_PATH, requestBody, "create");
3896
4083
  }
3897
4084
  async update(id, body) {
3898
4085
  return this.#writeThrough(UPDATE_PATH(id), body, "update");
@@ -3900,7 +4087,7 @@ var ExerciseLibrary = class {
3900
4087
  async #writeThrough(path, body, label) {
3901
4088
  await this.ensureFresh();
3902
4089
  const res = await this.#client.request("POST", path, { body });
3903
- if (!res.ok) throw new Error(`Exercise ${label} failed (HTTP ${res.status}).`);
4090
+ if (!res.ok) throw new Error(trainHeroicApiErrorMessage(`Exercise ${label}`, res.status, res.data));
3904
4091
  const ex = unwrapEnvelope(res.data);
3905
4092
  if (ex && typeof ex === "object") {
3906
4093
  checkResponse(exerciseResponseSchema, ex, `exercise ${label}`);
@@ -4607,10 +4794,10 @@ function registerAnalyticsTools(server, ctx) {
4607
4794
  function registerExerciseUpdate(server, index) {
4608
4795
  server.registerTool("exercise_update", {
4609
4796
  title: "Update custom exercise",
4610
- 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. Requires confirmation (elicitation, or confirm:true).",
4797
+ description: "Update a custom exercise (POST /2.0/coach/exercise/update/{id}) and write it through to the mirror. Uses the same writable fields as exercise_create; omitted fields are left unchanged. Only works for exercises with can_edit:1. Requires confirmation (elicitation, or confirm:true).",
4611
4798
  inputSchema: {
4612
4799
  id: idParam,
4613
- exercise: exerciseCreateSchema,
4800
+ exercise: exerciseUpdateSchema,
4614
4801
  confirm: z.boolean().optional()
4615
4802
  },
4616
4803
  outputSchema: toolOutputSchema(exerciseCreatedOutputSchema),
@@ -4690,7 +4877,7 @@ function registerExerciseTools(server, ctx) {
4690
4877
  registerExerciseReads(server, index);
4691
4878
  server.registerTool("exercise_create", {
4692
4879
  title: "Create custom exercise",
4693
- 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}.",
4880
+ 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}. The server supplies an empty points_of_performance value when it is omitted.",
4694
4881
  inputSchema: { exercise: exerciseCreateSchema },
4695
4882
  outputSchema: toolOutputSchema(exerciseCreatedOutputSchema),
4696
4883
  annotations: ADDITIVE
@@ -5028,7 +5215,7 @@ var JsonFileLibraryCache = class {
5028
5215
  };
5029
5216
  //#endregion
5030
5217
  //#region package.json
5031
- var version = "3.6.0";
5218
+ var version = "3.7.2";
5032
5219
  //#endregion
5033
5220
  //#region src/server.ts
5034
5221
  function main() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/coach-mcp",
3
- "version": "3.6.0",
3
+ "version": "3.7.2",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -20,14 +20,14 @@
20
20
  ],
21
21
  "dependencies": {
22
22
  "@modelcontextprotocol/server": "2.0.0",
23
- "zod": "^4.4.3",
24
- "@trainheroic-unofficial/core": "3.6.0",
25
- "@trainheroic-unofficial/js": "3.6.0"
23
+ "zod": "^4.6.3",
24
+ "@trainheroic-unofficial/js": "3.7.2",
25
+ "@trainheroic-unofficial/core": "3.7.2"
26
26
  },
27
27
  "devDependencies": {
28
- "@types/node": "^26.3.0",
29
- "tsdown": "^0.22.14",
30
- "tsx": "^4.23.12",
28
+ "@types/node": "^26.5.1",
29
+ "tsdown": "^0.23.0",
30
+ "tsx": "^4.23.13",
31
31
  "typescript": "^7.0.2",
32
32
  "vitest": "^4.1.11"
33
33
  },