@trainheroic-unofficial/coach-mcp 3.7.1 → 4.0.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.
Files changed (2) hide show
  1. package/dist/server.mjs +113 -19
  2. package/package.json +3 -3
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";
@@ -720,14 +720,26 @@ const exerciseSpecSchema = z.object({
720
720
  z.number(),
721
721
  z.string(),
722
722
  z.array(z.union([z.number(), z.string()]))
723
- ]).optional(),
723
+ ]).optional().describe("Primary slot values; may be reps, distance, or time. State primaryUnit."),
724
724
  sets: z.number().optional(),
725
- weight: z.union([z.number(), z.array(z.number())]).optional(),
725
+ weight: z.union([z.number(), z.array(z.number())]).optional().describe("Secondary slot values; may be weight or time. State secondaryUnit."),
726
+ primaryUnit: z.string().trim().min(1).optional().describe("Intended primary unit from exercise_resolve, such as reps, m, mi, or sec."),
727
+ secondaryUnit: z.string().trim().min(1).optional().describe("Intended secondary unit from exercise_resolve, such as lb or sec."),
726
728
  rpe: z.union([z.number(), z.string()]).optional(),
727
729
  instr: z.string().optional(),
728
730
  param_1_type: z.number().optional(),
729
731
  param_2_type: z.number().optional()
730
732
  }).superRefine((exercise, ctx) => {
733
+ if (exercise.reps !== void 0 && exercise.primaryUnit === void 0) ctx.addIssue({
734
+ code: "custom",
735
+ message: "primaryUnit is required when reps contains primary slot values.",
736
+ path: ["primaryUnit"]
737
+ });
738
+ if (exercise.weight !== void 0 && exercise.secondaryUnit === void 0) ctx.addIssue({
739
+ code: "custom",
740
+ message: "secondaryUnit is required when weight contains secondary slot values.",
741
+ path: ["secondaryUnit"]
742
+ });
731
743
  if (Array.isArray(exercise.reps) && Array.isArray(exercise.weight) && exercise.reps.length !== exercise.weight.length) ctx.addIssue({
732
744
  code: "custom",
733
745
  message: `Per-set reps and weight arrays must have the same length; received ${exercise.reps.length} reps and ${exercise.weight.length} weights.`,
@@ -1009,6 +1021,15 @@ async function apiCall(ctx, method, path, options, hint) {
1009
1021
  const NOT_CONFIRMED = "Not confirmed — the user declined. Nothing was changed.";
1010
1022
  /** Appended to the prompt so the fallback survives whichever way a client surfaces the request. */
1011
1023
  const FALLBACK_HINT = " (If you cannot show this prompt, re-run the tool with confirm:true once the user has agreed.)";
1024
+ const CONFIRMATION_REQUIRED = "Ask the user to approve this action, then retry the tool with confirm:true only after they agree. Nothing was changed.";
1025
+ /** `undefined` means a legacy request, whose capability check belongs to the SDK's shim. */
1026
+ function modernClientSupportsFormElicitation(ctx) {
1027
+ const envelope = ctx.mcpReq.envelope;
1028
+ if (envelope === void 0) return void 0;
1029
+ const elicitation = envelope[CLIENT_CAPABILITIES_META_KEY]?.elicitation;
1030
+ if (elicitation === void 0) return false;
1031
+ return elicitation.form !== void 0 || elicitation.url === void 0;
1032
+ }
1012
1033
  /**
1013
1034
  * Confirm a destructive/athlete-facing action.
1014
1035
  *
@@ -1024,14 +1045,15 @@ const FALLBACK_HINT = " (If you cannot show this prompt, re-run the tool with co
1024
1045
  * confirmation message ever needs data fetched first, that fetch must be idempotent.
1025
1046
  *
1026
1047
  * Written once in the 2026 `inputRequired` style: modern clients retry with `inputResponses`.
1027
- * A client that cannot elicit at all never reaches the denial below — the SDK rejects the
1028
- * request before the retry — so it must pass `confirm: true`, which is why the hint rides inside
1029
- * the prompt text itself.
1048
+ * MCP correctly rejects unsupported embedded requests with `-32021`. This application has an
1049
+ * alternate `confirm: true` flow, so a modern client that does not declare form elicitation gets
1050
+ * a model-readable tool error that tells it how to recover while the gate remains closed.
1030
1051
  */
1031
1052
  function confirmGate(ctx, message, confirmArg) {
1032
1053
  if (confirmArg === true) return void 0;
1033
1054
  if (acceptedContent(ctx.mcpReq.inputResponses, "confirm")?.confirm === true) return void 0;
1034
1055
  if (inputResponse(ctx.mcpReq.inputResponses, "confirm").kind !== "missing") return errorResult(NOT_CONFIRMED);
1056
+ if (modernClientSupportsFormElicitation(ctx) === false) return errorResult(`${message} ${CONFIRMATION_REQUIRED}`);
1035
1057
  const prompt = message + FALLBACK_HINT;
1036
1058
  return inputRequired({ inputRequests: { confirm: inputRequired.elicit({
1037
1059
  message: prompt,
@@ -2954,6 +2976,56 @@ function buildBlockPayload(blocks, workoutId) {
2954
2976
  function unitOr(t) {
2955
2977
  return unitLabel(t) ?? "?";
2956
2978
  }
2979
+ const UNIT_ALIASES = {
2980
+ rep: "reps",
2981
+ reps: "reps",
2982
+ lb: "lb",
2983
+ lbs: "lb",
2984
+ pound: "lb",
2985
+ pounds: "lb",
2986
+ sec: "sec",
2987
+ second: "sec",
2988
+ seconds: "sec",
2989
+ s: "sec",
2990
+ yd: "yd",
2991
+ yard: "yd",
2992
+ yards: "yd",
2993
+ m: "m",
2994
+ meter: "m",
2995
+ meters: "m",
2996
+ metre: "m",
2997
+ metres: "m",
2998
+ mi: "mi",
2999
+ mile: "mi",
3000
+ miles: "mi",
3001
+ ft: "ft",
3002
+ foot: "ft",
3003
+ feet: "ft",
3004
+ in: "in",
3005
+ inch: "in",
3006
+ inches: "in",
3007
+ bpm: "bpm",
3008
+ rpe: "RPE",
3009
+ "%max": "%max"
3010
+ };
3011
+ function statedUnit(value, label) {
3012
+ const normalized = UNIT_ALIASES[value.trim().toLowerCase()];
3013
+ if (normalized === void 0) throw new Error(`${label}: unknown unit '${value}'. Use a concrete exercise unit such as reps, lb, sec, m, or mi.`);
3014
+ return normalized;
3015
+ }
3016
+ function validateSlotUnit(label, field, stated, paramType, fixedType, allowAddedWeight = false) {
3017
+ if (stated === void 0) throw new Error(`${label}: ${field} is required for this value.`);
3018
+ const intended = statedUnit(stated, `${label} / ${field}`);
3019
+ const fixed = unitLabel(fixedType);
3020
+ if (intended !== fixed && !(allowAddedWeight && (fixedType === 0 || fixedType === null) && intended === "lb")) throw new Error(`${label}: ${field} ${intended} does not match the exercise's fixed ${fixed ?? "unset"} unit. Choose an exercise with the requested unit before building.`);
3021
+ if (paramType !== void 0 && unitLabel(paramType) !== intended) throw new Error(`${label}: ${field} ${intended} conflicts with param type ${paramType} (${unitLabel(paramType) ?? "unset"}).`);
3022
+ }
3023
+ /** Validate both populated slots against the library before any workout write. */
3024
+ function validateExerciseUnits(blockTitle, ex, defaults) {
3025
+ const label = `${blockTitle} / ${ex.title ?? ex.id}`;
3026
+ if (ex.reps !== void 0) validateSlotUnit(label, "primaryUnit", ex.primaryUnit, ex.param_1_type, defaults.param1);
3027
+ if (ex.weight !== void 0) validateSlotUnit(label, "secondaryUnit", ex.secondaryUnit, ex.param_2_type, defaults.param2, true);
3028
+ }
2957
3029
  /** Flag spec params the API will silently override to the exercise's fixed units. */
2958
3030
  function unitAdvisory(blockTitle, ex, defaults) {
2959
3031
  const notes = [];
@@ -2967,8 +3039,8 @@ function unitAdvisory(blockTitle, ex, defaults) {
2967
3039
  warnings.push(`${label}: param_1_type ${sentP1} (${u(sp1)}) is ignored — this exercise is fixed to ${u(defaults.param1)}; values render as ${u(defaults.param1)}.`);
2968
3040
  } else if (defaults.param1 !== 3 && defaults.param1 !== null) notes.push(`${label}: values are in ${u(defaults.param1)} (the exercise's fixed primary unit).`);
2969
3041
  if (ex.weight !== void 0 && ex.weight !== null) {
2970
- const sentP2 = Math.trunc(Number(ex.param_2_type ?? 1));
2971
3042
  const effP2 = defaults.param2 === 0 || defaults.param2 === null ? 1 : defaults.param2;
3043
+ const sentP2 = Math.trunc(Number(ex.param_2_type ?? effP2));
2972
3044
  if (sentP2 !== effP2) {
2973
3045
  if (sentP2 === 2 || sentP2 === 14) warnings.push(`${label}: ${u(sentP2)} does not stick on this exercise — it renders as ${u(effP2)}. Put it in the exercise 'instr' text and leave load blank.`);
2974
3046
  else warnings.push(`${label}: load renders as ${u(effP2)}, not ${u(sentP2)} (this exercise's secondary unit is fixed).`);
@@ -2980,24 +3052,23 @@ function unitAdvisory(blockTitle, ex, defaults) {
2980
3052
  };
2981
3053
  }
2982
3054
  /**
2983
- * Run unit advisories across a whole block list against an exercise index. Shared by the
2984
- * MCP workout_build tool and the CLI so both surface the same notes/warnings. Ensures the
2985
- * index is loaded first, otherwise the defaults map is empty on a cold index and every
2986
- * advisory is silently dropped.
3055
+ * Validate every populated value's stated unit against current TrainHeroic exercise data,
3056
+ * then collect non-blocking advisories. The write path calls this before creating a workout;
3057
+ * TrainHeroic silently replaces mismatched types.
2987
3058
  */
2988
3059
  async function collectAdvisories(blocks, index) {
2989
- await index.ensureFresh();
2990
3060
  const pairs = blocks.flatMap((b) => b.exercises.map((ex) => ({
2991
3061
  block: b,
2992
3062
  ex
2993
3063
  })));
2994
3064
  const ids = [...new Set(pairs.map((p) => Number(p.ex.id)).filter((id) => Number.isFinite(id)))];
2995
- const defaultsById = await index.defaultsMany(ids);
3065
+ const defaultsById = await index.currentDefaultsMany(ids);
2996
3066
  const notes = [];
2997
3067
  const warnings = [];
2998
3068
  pairs.forEach((p) => {
2999
3069
  const def = defaultsById.get(Number(p.ex.id));
3000
- if (!def) return;
3070
+ if (!def) throw new Error(`${p.block.title} / ${p.ex.title ?? p.ex.id}: exercise id ${p.ex.id} was not found in the library.`);
3071
+ validateExerciseUnits(p.block.title, p.ex, def);
3001
3072
  const advisory = unitAdvisory(p.block.title, p.ex, def);
3002
3073
  notes.push(...advisory.notes);
3003
3074
  warnings.push(...advisory.warnings);
@@ -3038,6 +3109,7 @@ async function buildSession(client, opts) {
3038
3109
  const validatedBlocks = z.array(blockSpecSchema).parse(opts.blocks);
3039
3110
  const splitSummary = setSplitSummary(validatedBlocks);
3040
3111
  if (splitSummary !== null && opts.confirmSetSplit !== true) throw new Error(`${splitSummary} Set confirmSetSplit:true to allow this change.`);
3112
+ const advisories = await collectAdvisories(validatedBlocks, opts.index);
3041
3113
  const blocks = splitSummary === null ? validatedBlocks : splitOversizedBlocks(validatedBlocks);
3042
3114
  const sess = await req(client, "POST", createPath(opts), {});
3043
3115
  checkResponse(sessionCreateResponseSchema, sess, "session create");
@@ -3061,7 +3133,8 @@ async function buildSession(client, opts) {
3061
3133
  if (opts.publish ?? false) await req(client, "POST", "/2.0/coach/calendar/programWorkout/publish", [pwId]);
3062
3134
  return {
3063
3135
  pwId,
3064
- workoutId
3136
+ workoutId,
3137
+ advisories
3065
3138
  };
3066
3139
  }
3067
3140
  /**
@@ -3935,6 +4008,25 @@ const CREATE_PATH = "/2.0/coach/exercise/create";
3935
4008
  const UPDATE_PATH = (id) => `/2.0/coach/exercise/update/${id}`;
3936
4009
  const DELETE_PATH = (id) => `/v5/exercises/${id}`;
3937
4010
  const TTL_MS = 6048e5;
4011
+ /** Read current parameter types without refreshing or trusting the search mirror. */
4012
+ async function fetchCurrentExerciseDefaults(client, ids) {
4013
+ if (ids.length === 0) return /* @__PURE__ */ new Map();
4014
+ const res = await client.request("GET", LIBRARY_PATH);
4015
+ if (!res.ok) throw new Error(`Exercise library fetch failed (HTTP ${res.status}).`);
4016
+ const list = asExerciseList(res.data);
4017
+ if (list.length === 0) throw new Error("Exercise library returned no rows.");
4018
+ checkResponse(exerciseLibraryResponseSchema, list, "exercise library");
4019
+ const requested = new Set(ids);
4020
+ const defaults = /* @__PURE__ */ new Map();
4021
+ for (const exercise of list) {
4022
+ const id = coerceInt(exercise.id);
4023
+ if (id !== null && requested.has(id)) defaults.set(id, {
4024
+ param1: coerceInt(exercise.param_1_type),
4025
+ param2: coerceInt(exercise.param_2_type)
4026
+ });
4027
+ }
4028
+ return defaults;
4029
+ }
3938
4030
  function toStored(ex) {
3939
4031
  const id = coerceInt(ex.id);
3940
4032
  if (id === null) return null;
@@ -4035,6 +4127,9 @@ var ExerciseLibrary = class {
4035
4127
  }
4036
4128
  return result;
4037
4129
  }
4130
+ async currentDefaultsMany(ids) {
4131
+ return fetchCurrentExerciseDefaults(this.#client, ids);
4132
+ }
4038
4133
  async search(query, limit = 20) {
4039
4134
  await this.ensureFresh();
4040
4135
  return this.#searchOnly(query, limit);
@@ -4903,7 +4998,7 @@ function registerExerciseTools(server, ctx) {
4903
4998
  function registerBuild(server, ctx) {
4904
4999
  server.registerTool("workout_build", {
4905
5000
  title: "Build a workout session (draft)",
4906
- description: "Build an UNPUBLISHED session from a spec (program -> session -> blocks -> exercises). Pass programId for a team/group calendar (list_teams → group_program), or athleteId to write on that roster athlete's coach calendar (resolved via /v5/calendars/athletes/{id} — the same calendar the coach web app opens from My Athletes). athleteId requires date. Two exercises in one block become a superset. A block with empty exercises and a non-empty block instruction is a text-only Circuit / Conditioning block (type 1). Add a block 'leaderboard' for a Red-Zone score, or a top-level 'instruction' for the session note (Coach Instructions). Returns the draft ids, a read-back, and unit advisories. Exercises above 10 sets are split into consecutive same-titled blocks and require confirmation (elicitation, or confirm:true). Review, then workout_publish.",
5001
+ description: "Build an UNPUBLISHED session from a spec (program -> session -> blocks -> exercises). Pass programId for a team/group calendar (list_teams → group_program), or athleteId to write on that roster athlete's coach calendar (resolved via /v5/calendars/athletes/{id} — the same calendar the coach web app opens from My Athletes). athleteId requires date. Two exercises in one block become a superset. A block with empty exercises and a non-empty block instruction is a text-only Circuit / Conditioning block (type 1). Add a block 'leaderboard' for a Red-Zone score, or a top-level 'instruction' for the session note (Coach Instructions). Returns the draft ids and a read-back. For each exercise, state primaryUnit when reps is present and secondaryUnit when weight is present; these are positional values, even when the unit is distance or time. Use exercise_resolve to check the exercise's fixed units before building. A mismatch fails before the draft is created. Exercises above 10 sets are split into consecutive same-titled blocks and require confirmation (elicitation, or confirm:true). Review, then workout_publish.",
4907
5002
  inputSchema: {
4908
5003
  programId: z.number().optional(),
4909
5004
  athleteId: idParam.optional(),
@@ -4931,20 +5026,19 @@ function registerBuild(server, ctx) {
4931
5026
  const opts = {
4932
5027
  programId: resolved,
4933
5028
  blocks: typed,
5029
+ index: ctx.index,
4934
5030
  publish: false
4935
5031
  };
4936
5032
  if (splitSummary !== null) opts.confirmSetSplit = true;
4937
5033
  if (date !== void 0) opts.date = parseWorkoutDate(date);
4938
5034
  if (timelineDay !== void 0) opts.timelineDay = timelineDay;
4939
5035
  if (instruction !== void 0) opts.instruction = instruction;
4940
- const advisories = await collectAdvisories(typed, ctx.index);
4941
5036
  const built = await buildSession(ctx.client, opts);
4942
5037
  const readback = opts.date ? await readSession(ctx.client, resolved, opts.date, built.pwId) : null;
4943
5038
  return jsonResult({
4944
5039
  ...built,
4945
5040
  programId: resolved,
4946
5041
  published: false,
4947
- advisories,
4948
5042
  readback,
4949
5043
  note: "Draft created (unpublished). Review, then call workout_publish to make it athlete-facing."
4950
5044
  });
@@ -5205,7 +5299,7 @@ var JsonFileLibraryCache = class {
5205
5299
  };
5206
5300
  //#endregion
5207
5301
  //#region package.json
5208
- var version = "3.7.1";
5302
+ var version = "4.0.0";
5209
5303
  //#endregion
5210
5304
  //#region src/server.ts
5211
5305
  function main() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/coach-mcp",
3
- "version": "3.7.1",
3
+ "version": "4.0.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -21,8 +21,8 @@
21
21
  "dependencies": {
22
22
  "@modelcontextprotocol/server": "2.0.0",
23
23
  "zod": "^4.6.3",
24
- "@trainheroic-unofficial/core": "3.7.1",
25
- "@trainheroic-unofficial/js": "3.7.1"
24
+ "@trainheroic-unofficial/core": "4.0.0",
25
+ "@trainheroic-unofficial/js": "4.0.0"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.5.1",