@trainheroic-unofficial/coach-mcp 1.7.4 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/server.mjs +114 -61
  2. package/package.json +8 -8
package/dist/server.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
1
+ import { McpServer, acceptedContent, inputRequired, inputResponse } from "@modelcontextprotocol/server";
2
+ import { serveStdio } from "@modelcontextprotocol/server/stdio";
3
3
  import process from "node:process";
4
4
  import { z } from "zod";
5
5
  import { mkdir, readFile, writeFile } from "node:fs/promises";
@@ -365,7 +365,11 @@ const DESTRUCTIVE = {
365
365
  destructiveHint: true,
366
366
  openWorldHint: true
367
367
  };
368
- /** Run a tool body, converting thrown errors into an in-band tool error. */
368
+ /**
369
+ * Run a tool body, converting thrown errors into an in-band tool error. Generic so a caller that
370
+ * only ever produces a `CallToolResult` keeps that narrower type instead of widening to the
371
+ * MRTR union — that is what lets `apiCall` delegate here rather than repeat this catch.
372
+ */
369
373
  async function attempt(fn) {
370
374
  try {
371
375
  return await fn();
@@ -511,32 +515,50 @@ async function apiCall(ctx, method, path, options, hint) {
511
515
  }
512
516
  //#endregion
513
517
  //#region ../core/src/confirm.ts
514
- const NOT_CONFIRMED = "Not confirmed. Re-run with confirm:true, or connect a client that supports MCP elicitation.";
515
518
  /**
516
- * Confirm a destructive/athlete-facing action. Prefers MCP elicitation (an
517
- * in-the-moment user prompt); falls back to an explicit confirm:true argument when
518
- * the client does not support elicitation. Never proceeds without one of the two.
519
+ * Returned when the user was asked and said no. It must not tell the model how to retry: the
520
+ * refusal is the answer. (The `confirm: true` fallback for clients that cannot elicit is
521
+ * advertised in each gated tool's description, which is where a model looks before calling.)
519
522
  */
520
- async function confirmGate(server, requestId, message, confirmArg) {
521
- if (confirmArg === true) return true;
522
- try {
523
- const result = await server.server.elicitInput({
524
- message,
525
- requestedSchema: {
526
- type: "object",
527
- properties: { confirm: {
528
- type: "boolean",
529
- title: "Confirm",
530
- description: message
531
- } },
532
- required: ["confirm"]
533
- }
534
- }, requestId === void 0 ? void 0 : { relatedRequestId: requestId });
535
- return result.action === "accept" && result.content?.confirm === true;
536
- } catch (err) {
537
- console.warn("MCP elicitation unavailable; treating as not confirmed", err);
538
- return false;
539
- }
523
+ const NOT_CONFIRMED = "Not confirmed — the user declined. Nothing was changed.";
524
+ /** Appended to the prompt so the fallback survives whichever way a client surfaces the request. */
525
+ const FALLBACK_HINT = " (If you cannot show this prompt, re-run the tool with confirm:true once the user has agreed.)";
526
+ /**
527
+ * Confirm a destructive/athlete-facing action.
528
+ *
529
+ * Prefers MCP multi-round-trip elicitation (`input_required`); falls back to an explicit
530
+ * `confirm:true` argument when the client already confirmed. Never proceeds without one of the two.
531
+ *
532
+ * Returns `undefined` when the action may proceed, otherwise the result to return to the client
533
+ * (`input_required` or an in-band denial).
534
+ *
535
+ * **Call this before any read or write.** MRTR is re-entrant: the client answers by re-sending
536
+ * the whole `tools/call`, and the stateless handler builds a fresh server and runs the handler
537
+ * from the top. Anything above the gate therefore executes twice on a confirmed action. If a
538
+ * confirmation message ever needs data fetched first, that fetch must be idempotent.
539
+ *
540
+ * Written once in the 2026 `inputRequired` style: modern clients retry with `inputResponses`.
541
+ * A client that cannot elicit at all never reaches the denial below — the SDK rejects the
542
+ * request before the retry — so it must pass `confirm: true`, which is why the hint rides inside
543
+ * the prompt text itself.
544
+ */
545
+ function confirmGate(ctx, message, confirmArg) {
546
+ if (confirmArg === true) return void 0;
547
+ if (acceptedContent(ctx.mcpReq.inputResponses, "confirm")?.confirm === true) return void 0;
548
+ if (inputResponse(ctx.mcpReq.inputResponses, "confirm").kind !== "missing") return errorResult(NOT_CONFIRMED);
549
+ const prompt = message + FALLBACK_HINT;
550
+ return inputRequired({ inputRequests: { confirm: inputRequired.elicit({
551
+ message: prompt,
552
+ requestedSchema: {
553
+ type: "object",
554
+ properties: { confirm: {
555
+ type: "boolean",
556
+ title: "Confirm",
557
+ description: prompt
558
+ } },
559
+ required: ["confirm"]
560
+ }
561
+ }) } });
540
562
  }
541
563
  //#endregion
542
564
  //#region ../core/src/instructions.ts
@@ -612,20 +634,27 @@ var TrainHeroicAuthError = class extends Error {
612
634
  name = "TrainHeroicAuthError";
613
635
  };
614
636
  /**
615
- * Authenticated TrainHeroic API client. Holds the coach credentials (from the grant's
616
- * encrypted props) and a lazily-acquired session token cached in memory for the life
617
- * of the Durable Object instance. On a 401/403 it re-logs in once and retries, since
637
+ * Authenticated TrainHeroic API client. Holds the credentials (on the hosted Worker, from the
638
+ * grant's encrypted props) and a lazily-acquired session token cached in memory for the life of
639
+ * *this client instance* — nothing longer. On a 401/403 it re-logs in once and retries, since
618
640
  * TrainHeroic has no refresh token and sessions expire after ~1-2h.
641
+ *
642
+ * Anything that wants a session to outlive one client owns that itself: pass a previously
643
+ * acquired token as `sessionId` and keep the new one via `options.onSession`. That matters
644
+ * wherever clients are short-lived — the hosted Worker builds one per HTTP request, and each CLI
645
+ * invocation is a fresh process — because otherwise every operation replays the password.
619
646
  */
620
647
  var TrainHeroicClient = class {
621
648
  #email;
622
649
  #password;
650
+ #onSession;
623
651
  #sessionId;
624
652
  #loginInFlight = null;
625
- constructor(email, password, sessionId = null) {
653
+ constructor(email, password, sessionId = null, options = {}) {
626
654
  this.#email = email;
627
655
  this.#password = password;
628
656
  this.#sessionId = sessionId;
657
+ this.#onSession = options.onSession;
629
658
  }
630
659
  get sessionId() {
631
660
  return this.#sessionId;
@@ -643,6 +672,9 @@ var TrainHeroicClient = class {
643
672
  const session = await loginTrainHeroic(this.#email, this.#password);
644
673
  if (!session) throw new TrainHeroicAuthError("TrainHeroic login failed");
645
674
  this.#sessionId = session.sessionId;
675
+ try {
676
+ this.#onSession?.(this.#sessionId);
677
+ } catch {}
646
678
  return this.#sessionId;
647
679
  }
648
680
  async request(method, path, options = {}) {
@@ -2726,7 +2758,7 @@ var MemoryLibraryCache = class {
2726
2758
  //#region ../js/src/exercise-index.ts
2727
2759
  const LIBRARY_PATH = "/v5/exerciseLibrary/all";
2728
2760
  const CREATE_PATH = "/2.0/coach/exercise/create";
2729
- const TTL_MS = 168 * 3600 * 1e3;
2761
+ const TTL_MS = 6048e5;
2730
2762
  function toStored(ex) {
2731
2763
  const id = coerceInt(ex.id);
2732
2764
  if (id === null) return null;
@@ -3172,7 +3204,8 @@ function registerAthleteTools(server, ctx) {
3172
3204
  const list = asEmailList(emails);
3173
3205
  if (list.length === 0) return errorResult("Provide at least one email address to invite.");
3174
3206
  const id = toId(teamId);
3175
- if (!await confirmGate(server, extra.requestId, `Invite ${list.join(", ")} to team ${id}? This emails them a real TrainHeroic invitation.`, confirm)) return errorResult(NOT_CONFIRMED);
3207
+ const blocked = confirmGate(extra, `Invite ${list.join(", ")} to team ${id}? This emails them a real TrainHeroic invitation.`, confirm);
3208
+ if (blocked) return blocked;
3176
3209
  return jsonResult({
3177
3210
  invited: true,
3178
3211
  teamId: id,
@@ -3193,7 +3226,8 @@ function registerAthleteTools(server, ctx) {
3193
3226
  annotations: DESTRUCTIVE
3194
3227
  }, ({ athleteIds, confirm }, extra) => attempt(async () => {
3195
3228
  const ids = athleteIds.map(toId);
3196
- if (!await confirmGate(server, extra.requestId, `Archive athlete(s) ${ids.join(", ")}? They leave the active roster (data is kept and restorable).`, confirm)) return errorResult(NOT_CONFIRMED);
3229
+ const blocked = confirmGate(extra, `Archive athlete(s) ${ids.join(", ")}? They leave the active roster (data is kept and restorable).`, confirm);
3230
+ if (blocked) return blocked;
3197
3231
  return apiCall(ctx, "PUT", "/v5/athletes/archive", { body: { athleteIds: ids } });
3198
3232
  }));
3199
3233
  server.registerTool("athlete_restore", {
@@ -3253,7 +3287,8 @@ function registerAthleteLogTools(server, ctx) {
3253
3287
  annotations: DESTRUCTIVE
3254
3288
  }, ({ athleteId, date, savedWorkoutSetId, results, confirm }, extra) => attempt(async () => {
3255
3289
  const aId = toId(athleteId);
3256
- if (!await confirmGate(server, extra.requestId, `Log results to athlete ${aId}'s saved workout set ${toId(savedWorkoutSetId)} on ${date}? This writes to their coach-visible training log.`, confirm)) return errorResult(NOT_CONFIRMED);
3290
+ const blocked = confirmGate(extra, `Log results to athlete ${aId}'s saved workout set ${toId(savedWorkoutSetId)} on ${date}? This writes to their coach-visible training log.`, confirm);
3291
+ if (blocked) return blocked;
3257
3292
  return jsonResult(await logForAthlete(ctx.client, {
3258
3293
  athleteId: aId,
3259
3294
  date,
@@ -3271,7 +3306,8 @@ function registerAthleteLogTools(server, ctx) {
3271
3306
  annotations: DESTRUCTIVE
3272
3307
  }, ({ athleteId, date, exercises, confirm }, extra) => attempt(async () => {
3273
3308
  const aId = toId(athleteId);
3274
- if (!await confirmGate(server, extra.requestId, `Log a session of ${exercises.length} exercise(s) for athlete ${aId} on ${date}? This writes to their coach-visible training log.`, confirm)) return errorResult(NOT_CONFIRMED);
3309
+ const blocked = confirmGate(extra, `Log a session of ${exercises.length} exercise(s) for athlete ${aId} on ${date}? This writes to their coach-visible training log.`, confirm);
3310
+ if (blocked) return blocked;
3275
3311
  return jsonResult(await logSessionForAthlete(ctx.client, {
3276
3312
  athleteId: aId,
3277
3313
  date,
@@ -3295,7 +3331,8 @@ function registerAthleteSwapTool(server, ctx) {
3295
3331
  }, ({ savedWorkoutSetExerciseId, exerciseId, confirm }, extra) => attempt(async () => {
3296
3332
  const sweId = toId(savedWorkoutSetExerciseId);
3297
3333
  const exId = toId(exerciseId);
3298
- if (!await confirmGate(server, extra.requestId, `Swap the exercise in saved workout slot ${sweId} to exercise ${exId}? This changes what this athlete is prescribed (their copy only).`, confirm)) return errorResult(NOT_CONFIRMED);
3334
+ const blocked = confirmGate(extra, `Swap the exercise in saved workout slot ${sweId} to exercise ${exId}? This changes what this athlete is prescribed (their copy only).`, confirm);
3335
+ if (blocked) return blocked;
3299
3336
  return jsonResult(await swapAthleteExercise(ctx.client, {
3300
3337
  savedWorkoutSetExerciseId: sweId,
3301
3338
  exerciseId: exId
@@ -3318,7 +3355,8 @@ function registerAthletePrescribeTool(server, ctx) {
3318
3355
  annotations: DESTRUCTIVE
3319
3356
  }, ({ athleteId, date, savedWorkoutSetId, results, confirm }, extra) => attempt(async () => {
3320
3357
  const aId = toId(athleteId);
3321
- if (!await confirmGate(server, extra.requestId, `Set prescribed values on athlete ${aId}'s saved workout set ${toId(savedWorkoutSetId)} on ${date}? This changes what this athlete is prescribed (their copy only); it does not mark the set done.`, confirm)) return errorResult(NOT_CONFIRMED);
3358
+ const blocked = confirmGate(extra, `Set prescribed values on athlete ${aId}'s saved workout set ${toId(savedWorkoutSetId)} on ${date}? This changes what this athlete is prescribed (their copy only); it does not mark the set done.`, confirm);
3359
+ if (blocked) return blocked;
3322
3360
  return jsonResult(await prescribeForAthlete(ctx.client, {
3323
3361
  athleteId: aId,
3324
3362
  date,
@@ -3364,7 +3402,8 @@ function registerTeamTools(server, ctx) {
3364
3402
  annotations: DESTRUCTIVE
3365
3403
  }, ({ teamId, confirm }, extra) => attempt(async () => {
3366
3404
  const id = toId(teamId);
3367
- if (!await confirmGate(server, extra.requestId, `Delete team ${id}? This removes the team and its calendar from the live account.`, confirm)) return errorResult(NOT_CONFIRMED);
3405
+ const blocked = confirmGate(extra, `Delete team ${id}? This removes the team and its calendar from the live account.`, confirm);
3406
+ if (blocked) return blocked;
3368
3407
  return apiCall(ctx, "DELETE", `/v5/teams/${id}`);
3369
3408
  }));
3370
3409
  server.registerTool("team_code_create", {
@@ -3386,7 +3425,8 @@ function registerTeamTools(server, ctx) {
3386
3425
  annotations: DESTRUCTIVE
3387
3426
  }, ({ codeId, confirm }, extra) => attempt(async () => {
3388
3427
  const id = toId(codeId);
3389
- if (!await confirmGate(server, extra.requestId, `Delete team join code ${id}? Athletes can no longer use it to join.`, confirm)) return errorResult(NOT_CONFIRMED);
3428
+ const blocked = confirmGate(extra, `Delete team join code ${id}? Athletes can no longer use it to join.`, confirm);
3429
+ if (blocked) return blocked;
3390
3430
  return apiCall(ctx, "DELETE", `/v5/teamCodes/${id}`);
3391
3431
  }));
3392
3432
  }
@@ -3562,7 +3602,8 @@ function registerBuild(server, ctx) {
3562
3602
  openWorldHint: true
3563
3603
  }
3564
3604
  }, ({ programId, date, pwId, confirm }, extra) => attempt(async () => {
3565
- if (!await confirmGate(server, extra.requestId, `Publish session ${pwId} on ${date}? This is athlete-facing and immediate.`, confirm)) return errorResult(NOT_CONFIRMED);
3605
+ const blocked = confirmGate(extra, `Publish session ${pwId} on ${date}? This is athlete-facing and immediate.`, confirm);
3606
+ if (blocked) return blocked;
3566
3607
  await publishSession(ctx.client, pwId);
3567
3608
  return jsonResult({
3568
3609
  published: pwId,
@@ -3586,7 +3627,8 @@ function registerLifecycle(server, ctx) {
3586
3627
  openWorldHint: true
3587
3628
  }
3588
3629
  }, ({ programId, pwId, confirm }, extra) => attempt(async () => {
3589
- if (!await confirmGate(server, extra.requestId, `Delete session ${pwId}? This removes it from the live calendar and is hard to undo.`, confirm)) return errorResult(NOT_CONFIRMED);
3630
+ const blocked = confirmGate(extra, `Delete session ${pwId}? This removes it from the live calendar and is hard to undo.`, confirm);
3631
+ if (blocked) return blocked;
3590
3632
  await removeSession(ctx.client, programId, pwId);
3591
3633
  return jsonResult({ removed: pwId });
3592
3634
  }));
@@ -3603,7 +3645,8 @@ function registerLifecycle(server, ctx) {
3603
3645
  openWorldHint: true
3604
3646
  }
3605
3647
  }, ({ pwId, confirm }, extra) => attempt(async () => {
3606
- if (!await confirmGate(server, extra.requestId, `Unpublish session ${pwId}? Athletes will no longer see it.`, confirm)) return errorResult(NOT_CONFIRMED);
3648
+ const blocked = confirmGate(extra, `Unpublish session ${pwId}? Athletes will no longer see it.`, confirm);
3649
+ if (blocked) return blocked;
3607
3650
  return apiCall(ctx, "POST", `/2.0/coach/calendar/programWorkout/unPublish/${pwId}`);
3608
3651
  }));
3609
3652
  server.registerTool("session_copy", {
@@ -3692,7 +3735,8 @@ function registerWrites(server, ctx) {
3692
3735
  annotations: DESTRUCTIVE
3693
3736
  }, ({ streamId, text, replyTo, confirm }, extra) => attempt(async () => {
3694
3737
  const id = toId(streamId);
3695
- if (!await confirmGate(server, extra.requestId, `Send this message to stream ${id}? It is athlete-facing and immediate.`, confirm)) return errorResult(NOT_CONFIRMED);
3738
+ const blocked = confirmGate(extra, `Send this message to stream ${id}? It is athlete-facing and immediate.`, confirm);
3739
+ if (blocked) return blocked;
3696
3740
  return jsonResult({
3697
3741
  sent: true,
3698
3742
  comment: await sendComment(ctx.client, id, text, replyTo === void 0 ? null : toId(replyTo))
@@ -3708,7 +3752,8 @@ function registerWrites(server, ctx) {
3708
3752
  },
3709
3753
  annotations: DESTRUCTIVE
3710
3754
  }, ({ streamId, commentId, confirm }, extra) => attempt(async () => {
3711
- if (!await confirmGate(server, extra.requestId, `Delete comment ${toId(commentId)} from stream ${toId(streamId)}? Acts on the live account.`, confirm)) return errorResult(NOT_CONFIRMED);
3755
+ const blocked = confirmGate(extra, `Delete comment ${toId(commentId)} from stream ${toId(streamId)}? Acts on the live account.`, confirm);
3756
+ if (blocked) return blocked;
3712
3757
  return jsonResult({
3713
3758
  deleted: true,
3714
3759
  response: await deleteComment(ctx.client, toId(streamId), toId(commentId))
@@ -3721,6 +3766,19 @@ function registerMessagingTools(server, ctx) {
3721
3766
  registerWrites(server, ctx);
3722
3767
  }
3723
3768
  //#endregion
3769
+ //#region ../core/src/tools/coach.ts
3770
+ /** Register the full coach tool surface (roster, teams, programs, exercises, messaging). */
3771
+ function registerCoachTools(server, ctx) {
3772
+ registerReadTools(server, ctx);
3773
+ registerMainLiftTools(server, ctx);
3774
+ registerAthleteTools(server, ctx);
3775
+ registerTeamTools(server, ctx);
3776
+ registerAnalyticsTools(server, ctx);
3777
+ registerExerciseTools(server, ctx);
3778
+ registerWorkoutTools(server, ctx);
3779
+ registerMessagingTools(server, ctx);
3780
+ }
3781
+ //#endregion
3724
3782
  //#region ../js/src/node.ts
3725
3783
  /** Default exercise-cache path, overridable with TRAINHEROIC_CACHE_FILE. */
3726
3784
  function defaultCachePath() {
@@ -3746,10 +3804,10 @@ var JsonFileLibraryCache = class {
3746
3804
  };
3747
3805
  //#endregion
3748
3806
  //#region package.json
3749
- var version = "1.7.4";
3807
+ var version = "2.0.1";
3750
3808
  //#endregion
3751
3809
  //#region src/server.ts
3752
- async function main() {
3810
+ function main() {
3753
3811
  const email = process.env.TRAINHEROIC_EMAIL;
3754
3812
  const password = process.env.TRAINHEROIC_PASSWORD;
3755
3813
  if (!email || !password) {
@@ -3761,20 +3819,15 @@ async function main() {
3761
3819
  client,
3762
3820
  index: new ExerciseLibrary(client, new JsonFileLibraryCache())
3763
3821
  };
3764
- const server = new McpServer({
3765
- name: "trainheroic-local",
3766
- version
3767
- }, { instructions: SERVER_INSTRUCTIONS });
3768
- registerReadTools(server, ctx);
3769
- registerMainLiftTools(server, ctx);
3770
- registerAthleteTools(server, ctx);
3771
- registerTeamTools(server, ctx);
3772
- registerAnalyticsTools(server, ctx);
3773
- registerExerciseTools(server, ctx);
3774
- registerWorkoutTools(server, ctx);
3775
- registerMessagingTools(server, ctx);
3776
- await server.connect(new StdioServerTransport());
3822
+ serveStdio(() => {
3823
+ const server = new McpServer({
3824
+ name: "trainheroic-local",
3825
+ version
3826
+ }, { instructions: SERVER_INSTRUCTIONS });
3827
+ registerCoachTools(server, ctx);
3828
+ return server;
3829
+ });
3777
3830
  }
3778
- await main();
3831
+ main();
3779
3832
  //#endregion
3780
3833
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/coach-mcp",
3
- "version": "1.7.4",
3
+ "version": "2.0.1",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -19,16 +19,16 @@
19
19
  "dist"
20
20
  ],
21
21
  "dependencies": {
22
- "@modelcontextprotocol/sdk": "^1.29.0",
22
+ "@modelcontextprotocol/server": "2.0.0",
23
23
  "zod": "^4.4.3",
24
- "@trainheroic-unofficial/core": "1.7.4",
25
- "@trainheroic-unofficial/js": "1.7.4"
24
+ "@trainheroic-unofficial/core": "2.0.1",
25
+ "@trainheroic-unofficial/js": "2.0.1"
26
26
  },
27
27
  "devDependencies": {
28
- "@types/node": "^26.1.0",
29
- "tsdown": "^0.22.3",
30
- "tsx": "^4.23.0",
31
- "typescript": "^6.0.3",
28
+ "@types/node": "^26.1.2",
29
+ "tsdown": "^0.22.14",
30
+ "tsx": "^4.23.4",
31
+ "typescript": "^7.0.2",
32
32
  "vitest": "^4.1.10"
33
33
  },
34
34
  "scripts": {