@trainheroic-unofficial/coach-mcp 0.2.0 → 0.4.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 +597 -122
  2. package/package.json +3 -3
package/dist/server.mjs CHANGED
@@ -15,6 +15,157 @@ const idSchema = z.union([z.string(), z.number()]);
15
15
  */
16
16
  const idArgSchema = z.union([z.number().int(), z.string().regex(/^\d+$/u)]);
17
17
  //#endregion
18
+ //#region ../dto/src/athlete.ts
19
+ const intLike$1 = z.union([z.number(), z.string()]);
20
+ const intLikeOrNull$1 = z.union([
21
+ z.number(),
22
+ z.string(),
23
+ z.null()
24
+ ]);
25
+ const numLikeOrNull = z.union([
26
+ z.number(),
27
+ z.string(),
28
+ z.null()
29
+ ]);
30
+ z.looseObject({
31
+ id: intLike$1,
32
+ roles: z.array(z.string()).optional(),
33
+ org_id: intLikeOrNull$1.optional()
34
+ });
35
+ z.looseObject({
36
+ reps_sum: z.number().optional(),
37
+ volume_sum: z.number().optional(),
38
+ sessions_count: z.number().optional(),
39
+ first_logged_date: z.string().optional(),
40
+ last_logged_date: z.string().optional(),
41
+ duration_hours: z.number().optional()
42
+ });
43
+ z.looseObject({
44
+ id: intLike$1,
45
+ email: z.string().optional(),
46
+ name_first: z.string().optional(),
47
+ name_last: z.string().optional(),
48
+ username: z.string().optional(),
49
+ gender: z.string().optional(),
50
+ date_of_birth: z.string().optional(),
51
+ use_metric: z.boolean().optional()
52
+ });
53
+ z.looseObject({ id: intLike$1 });
54
+ /** One item of `/2.0/athlete/workingMax` — the athlete's working max for an exercise. */
55
+ const athleteWorkingMaxSchema = z.looseObject({
56
+ exercise_id: intLike$1,
57
+ title: z.string().optional(),
58
+ param_type: intLikeOrNull$1.optional(),
59
+ value: numLikeOrNull.optional(),
60
+ type_suffix: z.string().optional(),
61
+ working_max_id: intLikeOrNull$1.optional()
62
+ });
63
+ z.array(athleteWorkingMaxSchema);
64
+ /** One item of `/v5/users/exercises/history` — an exercise the athlete has logged. */
65
+ const exerciseHistoryListItemSchema = z.looseObject({
66
+ id: intLike$1,
67
+ title: z.string(),
68
+ isCircuit: z.boolean().optional(),
69
+ prescription: z.string().optional(),
70
+ param1Type: intLikeOrNull$1.optional(),
71
+ param2Type: intLikeOrNull$1.optional()
72
+ });
73
+ z.array(exerciseHistoryListItemSchema);
74
+ /** A single completed set inside a history entry (`/v5/exercises/{id}/history`). */
75
+ const historySetSchema = z.looseObject({
76
+ setNumber: z.number(),
77
+ formattedValue: z.string().optional(),
78
+ rawValue1: numLikeOrNull.optional(),
79
+ rawValue2: numLikeOrNull.optional(),
80
+ savedWorkoutSetExerciseId: intLike$1.optional()
81
+ });
82
+ /** A best rep-max derived for a history entry. */
83
+ const repMaxSchema = z.looseObject({
84
+ reps: z.number(),
85
+ weight: z.number()
86
+ });
87
+ /** One performed session of an exercise (`/v5/exercises/{id}/history` → `history[]`). */
88
+ const historyEntrySchema = z.looseObject({
89
+ dateCompleted: z.string(),
90
+ notes: z.string().nullable().optional(),
91
+ isLift: z.boolean().optional(),
92
+ param1Type: intLikeOrNull$1.optional(),
93
+ param2Type: intLikeOrNull$1.optional(),
94
+ savedWorkoutSetExerciseId: intLike$1.optional(),
95
+ teamId: intLikeOrNull$1.optional(),
96
+ programWorkoutId: intLikeOrNull$1.optional(),
97
+ abr: z.string().optional(),
98
+ bestEstimated1RM: z.number().optional(),
99
+ repMaxes: z.array(repMaxSchema).optional(),
100
+ sets: z.array(historySetSchema).optional()
101
+ });
102
+ /** A lifetime PR row from `/v5/exercises/{id}/history` → `liftPRs[]`. */
103
+ const liftPRSchema = z.looseObject({
104
+ weight: z.number().optional(),
105
+ savedWorkoutSetExerciseId: intLike$1.optional(),
106
+ setNumber: z.number().optional(),
107
+ dateCompleted: z.string().optional(),
108
+ reps: z.number().optional(),
109
+ units: z.string().optional(),
110
+ isMetric: z.boolean().optional(),
111
+ description: z.string().optional()
112
+ });
113
+ z.looseObject({
114
+ liftPRs: z.array(liftPRSchema).optional(),
115
+ singleParamPRs: z.array(z.unknown()).optional(),
116
+ history: z.array(historyEntrySchema).optional()
117
+ });
118
+ /** One item of `/v5/exercises/{id}/personalRecords` — a standards-filtered PR. */
119
+ const personalRecordSchema = z.looseObject({
120
+ id: intLike$1.optional(),
121
+ savedWorkoutSetExerciseId: intLike$1.optional(),
122
+ setNumber: z.number().optional(),
123
+ reps: z.number().optional(),
124
+ weight: z.number().optional(),
125
+ scaledWeight: z.number().optional(),
126
+ units: z.string().optional(),
127
+ isMetric: z.boolean().optional()
128
+ });
129
+ z.array(personalRecordSchema);
130
+ z.looseObject({
131
+ isLift: z.boolean().optional(),
132
+ lastPerformance: z.unknown().optional(),
133
+ personalRecord: z.unknown().optional()
134
+ });
135
+ /**
136
+ * One item of `/3.0/athlete/programworkout/range` — a scheduled/completed workout. The deep
137
+ * `summarizedSavedWorkout` tree is left loose: the presenter in `js` flattens it, so dto only
138
+ * pins the top-level fields the warehouse and presenter key off.
139
+ */
140
+ const programWorkoutSchema = z.looseObject({
141
+ id: intLike$1,
142
+ date: z.string().optional(),
143
+ workout_title: z.string().optional(),
144
+ program_id: intLikeOrNull$1.optional(),
145
+ program_title: z.string().optional(),
146
+ team_id: intLikeOrNull$1.optional(),
147
+ team_title: z.string().optional(),
148
+ summarizedSavedWorkout: z.unknown().optional()
149
+ });
150
+ z.array(programWorkoutSchema);
151
+ /** A `YYYY-MM-DD` date argument. The single definition reused across athlete tool inputs. */
152
+ const dateString = z.string().regex(/^\d{4}-\d{2}-\d{2}$/u, "expected YYYY-MM-DD");
153
+ z.object({
154
+ startDate: dateString,
155
+ endDate: dateString
156
+ });
157
+ z.object({
158
+ date: dateString,
159
+ savedWorkoutSetId: idArgSchema,
160
+ results: z.array(z.object({
161
+ savedWorkoutSetExerciseId: idArgSchema,
162
+ sets: z.array(z.object({
163
+ param1: z.union([z.number(), z.string()]).optional(),
164
+ param2: z.union([z.number(), z.string()]).optional()
165
+ })).min(1)
166
+ })).min(1)
167
+ });
168
+ //#endregion
18
169
  //#region ../dto/src/exercise.ts
19
170
  /** Body for creating a custom exercise; extra fields the API accepts are preserved. */
20
171
  const exerciseCreateSchema = z.looseObject({
@@ -335,12 +486,12 @@ const SIMPLE_GETS = [
335
486
  {
336
487
  name: "analytics_categories",
337
488
  title: "Analytics categories",
338
- description: "Lists available analytics types. Pull the data via th_request POST /v5/analytics/*.",
489
+ description: "Lists available analytics types. Pull a report with analytics_query (pick the matching metric).",
339
490
  path: "/v5/analytics"
340
491
  }
341
492
  ];
342
- /** Read-only coach/athlete queries. Exercise lookups live in the exercise store tools. */
343
- function registerReadTools(server, ctx) {
493
+ /** Roster-level reads: the fixed GETs plus the filterable athlete and team lists. */
494
+ function registerRosterReads(server, ctx) {
344
495
  for (const t of SIMPLE_GETS) server.registerTool(t.name, {
345
496
  title: t.title,
346
497
  description: t.description,
@@ -393,6 +544,9 @@ function registerReadTools(server, ctx) {
393
544
  const query = qs.toString();
394
545
  return apiCall(ctx, "GET", `/1.0/coach/teams${query ? `?${query}` : ""}`);
395
546
  });
547
+ }
548
+ /** Reads scoped to a single entity (team, program, athlete) plus the activity feed. */
549
+ function registerEntityReads(server, ctx) {
396
550
  server.registerTool("get_team", {
397
551
  title: "Get team",
398
552
  description: "Full team object by team id.",
@@ -412,112 +566,10 @@ function registerReadTools(server, ctx) {
412
566
  annotations: READ
413
567
  }, ({ programId }) => apiCall(ctx, "GET", `/3.0/coach/program/${enc(programId)}`, void 0, "This is a large, deep object. If it is truncated, fetch a narrower view (a specific session) instead."));
414
568
  }
415
- //#endregion
416
- //#region ../core/src/tools/raw.ts
417
- /**
418
- * Escape hatch covering every endpoint without a dedicated tool (e.g. the analytics
419
- * POSTs). GET is ungated; mutating methods go through the same confirmation gate as
420
- * the dedicated destructive tools so this cannot be used to bypass it.
421
- */
422
- function registerRawTools(server, ctx) {
423
- server.registerTool("th_request", {
424
- title: "Raw TrainHeroic request",
425
- description: "Call any TrainHeroic endpoint directly. `path` is everything after the host. `base` selects the host: 'coach' = api.trainheroic.com (default), 'apis' = apis.trainheroic.com. Prefer dedicated tools where they exist. POST/PUT/DELETE act on the live account and require confirmation.",
426
- inputSchema: {
427
- method: z.enum([
428
- "GET",
429
- "POST",
430
- "PUT",
431
- "DELETE"
432
- ]),
433
- path: z.string().min(1),
434
- body: z.unknown().optional(),
435
- base: z.enum(["coach", "apis"]).optional(),
436
- confirm: z.boolean().optional()
437
- },
438
- annotations: DESTRUCTIVE
439
- }, async ({ method, path, body, base, confirm }, extra) => {
440
- if (method !== "GET") {
441
- if (!await confirmGate(server, extra.requestId, `Run ${method} ${path} against the live TrainHeroic account?`, confirm)) return errorResult(NOT_CONFIRMED);
442
- }
443
- const options = {};
444
- if (body !== void 0) options.body = body;
445
- if (base !== void 0) options.base = base;
446
- return apiCall(ctx, method, path, options, "Large or unfiltered response. Add query params to narrow it, or use a dedicated tool for this endpoint if one exists.");
447
- });
448
- }
449
- //#endregion
450
- //#region ../core/src/tools/exercises.ts
451
- /**
452
- * Exercise library tools over the ExerciseIndex — a D1 mirror on the hosted server, an
453
- * on-disk/in-memory cache locally. The descriptions stay at the interface level so they
454
- * read correctly on both backends.
455
- */
456
- function registerExerciseTools(server, ctx) {
457
- const index = ctx.index;
458
- server.registerTool("exercise_resolve", {
459
- title: "Resolve exercise name",
460
- description: "Map a name to an exercise id via the local mirror. Returns the match plus ranked candidates; when ambiguous, match is null and you should pick from candidates. Units (param_1_unit/param_2_unit) are fixed per exercise — check them before prescribing.",
461
- inputSchema: { name: z.string().min(1) },
462
- annotations: READ
463
- }, ({ name }) => attempt(async () => jsonResult(await index.resolve(name))));
464
- server.registerTool("exercise_search", {
465
- title: "Search exercises",
466
- description: "Ranked fuzzy search over exercise titles. Returns candidates with units.",
467
- inputSchema: {
468
- query: z.string().min(1),
469
- limit: z.number().int().positive().max(100).optional()
470
- },
471
- annotations: READ
472
- }, ({ query, limit }) => attempt(async () => jsonResult(await index.search(query, limit ?? 20))));
473
- server.registerTool("exercise_get", {
474
- title: "Get exercise",
475
- description: "Full exercise object (with units) by id.",
476
- inputSchema: { id: idParam },
477
- annotations: READ
478
- }, ({ id }) => attempt(async () => {
479
- const ex = await index.get(toId(id));
480
- return ex ? jsonResult(ex) : errorResult(`No exercise with id ${toId(id)}.`);
481
- }));
482
- server.registerTool("exercise_sync", {
483
- title: "Sync exercise library",
484
- description: "Refresh the cached exercise index from TrainHeroic.",
485
- inputSchema: { force: z.boolean().optional() },
486
- annotations: SYNC
487
- }, ({ force }) => attempt(async () => {
488
- if (force ?? false) return jsonResult(await index.refresh());
489
- await index.ensureFresh();
490
- return jsonResult(await index.stats());
491
- }));
492
- server.registerTool("exercise_create", {
493
- title: "Create custom exercise",
494
- 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}.",
495
- inputSchema: { exercise: exerciseCreateSchema },
496
- annotations: {
497
- readOnlyHint: false,
498
- destructiveHint: false,
499
- openWorldHint: true
500
- }
501
- }, ({ exercise }) => attempt(async () => jsonResult(await index.create(exercise))));
502
- server.registerTool("exercise_forget", {
503
- title: "Forget exercise (cache only)",
504
- description: "Remove an exercise from the local mirror only. Run after deleting it via the API.",
505
- inputSchema: { id: idParam },
506
- annotations: {
507
- readOnlyHint: false,
508
- idempotentHint: true,
509
- openWorldHint: false
510
- }
511
- }, ({ id }) => attempt(async () => {
512
- await index.recordDelete(toId(id));
513
- return jsonResult({ forgotten: toId(id) });
514
- }));
515
- server.registerTool("store_stats", {
516
- title: "Exercise index stats",
517
- description: "Row counts and sync state for the cached exercise index.",
518
- inputSchema: {},
519
- annotations: READ
520
- }, () => attempt(async () => jsonResult(await index.stats())));
569
+ /** Read-only coach/athlete queries. Exercise lookups live in the exercise store tools. */
570
+ function registerReadTools(server, ctx) {
571
+ registerRosterReads(server, ctx);
572
+ registerEntityReads(server, ctx);
521
573
  }
522
574
  //#endregion
523
575
  //#region ../js/src/auth.ts
@@ -682,12 +734,31 @@ function unitLabel(paramType) {
682
734
  if (t === null) return null;
683
735
  return PARAM_UNIT[t] ?? null;
684
736
  }
685
- /** Annotate a row with human-readable units for display. */
737
+ /**
738
+ * Fixed measurement units for an exercise, ordered by entry slot (param 1, then param 2).
739
+ * Positional, not semantic: some exercises reverse the slots, so the array is not labelled
740
+ * by role. A null entry is an unset slot.
741
+ */
742
+ function exerciseUnits(param1, param2) {
743
+ return [unitLabel(param1), unitLabel(param2)];
744
+ }
745
+ /** Present a row for display: drop the raw param-type codes, surface units positionally. */
686
746
  function withUnits(row) {
747
+ const { param_1_type, param_2_type, ...rest } = row;
687
748
  return {
688
- ...row,
689
- param_1_unit: unitLabel(row.param_1_type),
690
- param_2_unit: unitLabel(row.param_2_type)
749
+ ...rest,
750
+ units: exerciseUnits(param_1_type, param_2_type)
751
+ };
752
+ }
753
+ /**
754
+ * Present a full raw exercise object for display: drop the raw param-type codes and add the
755
+ * positional `units` array. Keeps every other field of the raw object intact.
756
+ */
757
+ function presentExercise(raw) {
758
+ const { param_1_type, param_2_type, ...rest } = raw;
759
+ return {
760
+ ...rest,
761
+ units: exerciseUnits(param_1_type, param_2_type)
691
762
  };
692
763
  }
693
764
  function buildSearchText(title) {
@@ -749,7 +820,7 @@ function rankSearch(rows, query, limit) {
749
820
  if (title.startsWith(q)) score += 100;
750
821
  for (const tok of tokens) if (title.includes(tok)) score += 10;
751
822
  score -= title.length * .05;
752
- if (row.can_edit === 0) score += 1;
823
+ if ((row.can_edit ?? 0) === 0) score += 1;
753
824
  return {
754
825
  row,
755
826
  score
@@ -1243,10 +1314,7 @@ var ExerciseLibrary = class {
1243
1314
  await this.ensureFresh();
1244
1315
  const s = this.#byId.get(id);
1245
1316
  if (!s) return null;
1246
- const full = { ...s.raw };
1247
- full.param_1_unit = unitLabel(full.param_1_type);
1248
- full.param_2_unit = unitLabel(full.param_2_type);
1249
- return full;
1317
+ return presentExercise(s.raw);
1250
1318
  }
1251
1319
  async defaults(id) {
1252
1320
  const s = this.#byId.get(id);
@@ -1326,9 +1394,351 @@ var ExerciseLibrary = class {
1326
1394
  }
1327
1395
  };
1328
1396
  //#endregion
1397
+ //#region ../core/src/tools/athletes.ts
1398
+ const DEFAULT_INVITE_MESSAGE = "Follow these steps and you'll be set up and ready to go!";
1399
+ /** Normalize one-or-many emails into a deduped, trimmed list. */
1400
+ function asEmailList(emails) {
1401
+ return [...new Set((Array.isArray(emails) ? emails : [emails]).map((e) => e.trim()).filter((e) => e.length > 0))];
1402
+ }
1403
+ /**
1404
+ * Athlete management. TrainHeroic has no "create athlete" primitive: a coach invites a
1405
+ * person by email to a team, and the athlete record only exists once they accept and set
1406
+ * their own name. So the create path is the two-step invite from the API reference:
1407
+ * validate the address (POST /v5/emails/validate), then inviteToTeam
1408
+ * (POST /v5/athletes/inviteToTeam). Both act on the live account, so the invite is gated.
1409
+ */
1410
+ function registerAthleteTools(server, ctx) {
1411
+ server.registerTool("athlete_invite", {
1412
+ title: "Invite an athlete",
1413
+ description: "Add athletes by emailing them a TrainHeroic team invitation — this is how you 'create' an athlete; there is no other create path, and no name is collected here (the athlete sets their own on accept). Targets a team by id, so list_teams first if you need one. Validates each address, then sends the invite. ATHLETE-FACING and immediate; requires confirmation (elicitation, or confirm:true).",
1414
+ inputSchema: {
1415
+ teamId: idParam,
1416
+ emails: z.union([z.string(), z.array(z.string()).min(1)]),
1417
+ message: z.string().optional(),
1418
+ confirm: z.boolean().optional()
1419
+ },
1420
+ annotations: DESTRUCTIVE
1421
+ }, ({ teamId, emails, message, confirm }, extra) => attempt(async () => {
1422
+ const list = asEmailList(emails);
1423
+ if (list.length === 0) return errorResult("Provide at least one email address to invite.");
1424
+ const id = toId(teamId);
1425
+ if (!await confirmGate(server, extra.requestId, `Invite ${list.join(", ")} to team ${id}? This emails them a real TrainHeroic invitation.`, confirm)) return errorResult(NOT_CONFIRMED);
1426
+ const validation = await ctx.client.request("POST", "/v5/emails/validate", { body: { emails: list.join(",") } });
1427
+ if (!validation.ok) {
1428
+ const detail = typeof validation.data === "string" ? validation.data : JSON.stringify(validation.data);
1429
+ return errorResult(`Email validation failed (HTTP ${validation.status}): ${detail}`);
1430
+ }
1431
+ const valid = Array.isArray(validation.data) ? validation.data : list;
1432
+ if (valid.length === 0) return errorResult(`No valid addresses among: ${list.join(", ")}. They may be malformed or already on the team.`);
1433
+ const invite = await ctx.client.request("POST", "/v5/athletes/inviteToTeam", { body: {
1434
+ teamType: 0,
1435
+ teamId: id,
1436
+ orgId: null,
1437
+ emails: valid,
1438
+ message: message ?? DEFAULT_INVITE_MESSAGE
1439
+ } });
1440
+ if (!invite.ok) {
1441
+ const detail = typeof invite.data === "string" ? invite.data : JSON.stringify(invite.data);
1442
+ return errorResult(`Invite failed (HTTP ${invite.status}): ${detail}`);
1443
+ }
1444
+ return jsonResult({
1445
+ invited: true,
1446
+ teamId: id,
1447
+ result: invite.data
1448
+ });
1449
+ }));
1450
+ server.registerTool("athlete_archive", {
1451
+ title: "Archive athletes",
1452
+ description: "Remove one or more athletes from the active roster (PUT /v5/athletes/archive). Their data is preserved and they can be restored. Acts on the live account; requires confirmation (elicitation, or confirm:true).",
1453
+ inputSchema: {
1454
+ athleteIds: z.array(idParam).min(1),
1455
+ confirm: z.boolean().optional()
1456
+ },
1457
+ annotations: DESTRUCTIVE
1458
+ }, ({ athleteIds, confirm }, extra) => attempt(async () => {
1459
+ const ids = athleteIds.map(toId);
1460
+ 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);
1461
+ return apiCall(ctx, "PUT", "/v5/athletes/archive", { body: { athleteIds: ids } });
1462
+ }));
1463
+ server.registerTool("athlete_restore", {
1464
+ title: "Restore athletes",
1465
+ description: "Restore previously archived athletes to the active roster (PUT /v5/athletes/restore).",
1466
+ inputSchema: { athleteIds: z.array(idParam).min(1) },
1467
+ annotations: {
1468
+ readOnlyHint: false,
1469
+ idempotentHint: true,
1470
+ destructiveHint: false,
1471
+ openWorldHint: true
1472
+ }
1473
+ }, ({ athleteIds }) => apiCall(ctx, "PUT", "/v5/athletes/restore", { body: { athleteIds: athleteIds.map(toId) } }));
1474
+ }
1475
+ //#endregion
1476
+ //#region ../core/src/tools/teams.ts
1477
+ const ADDITIVE = {
1478
+ readOnlyHint: false,
1479
+ destructiveHint: false,
1480
+ openWorldHint: true
1481
+ };
1482
+ /**
1483
+ * Team write tools. The team reads (list_teams, get_team, list_team_codes) live in
1484
+ * reads.ts; this module covers create/rename/delete plus the join-code lifecycle.
1485
+ */
1486
+ function registerTeamTools(server, ctx) {
1487
+ server.registerTool("team_create", {
1488
+ title: "Create a team",
1489
+ 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.",
1490
+ inputSchema: { title: z.string().min(1) },
1491
+ annotations: ADDITIVE
1492
+ }, ({ title }) => apiCall(ctx, "POST", "/1.0/coach/team/createWithTitleAndCode", { body: { title } }));
1493
+ server.registerTool("team_update", {
1494
+ title: "Rename a team",
1495
+ description: "Update a team's settings, e.g. its title (PUT /v5/teams/{teamId}).",
1496
+ inputSchema: {
1497
+ teamId: idParam,
1498
+ title: z.string().min(1)
1499
+ },
1500
+ annotations: ADDITIVE
1501
+ }, ({ teamId, title }) => apiCall(ctx, "PUT", `/v5/teams/${toId(teamId)}`, { body: { title } }));
1502
+ server.registerTool("team_delete", {
1503
+ title: "Delete a team",
1504
+ description: "Delete a team (DELETE /v5/teams/{teamId}). Removes the team and its calendar from the live account; hard to undo. Requires confirmation (elicitation, or confirm:true).",
1505
+ inputSchema: {
1506
+ teamId: idParam,
1507
+ confirm: z.boolean().optional()
1508
+ },
1509
+ annotations: DESTRUCTIVE
1510
+ }, ({ teamId, confirm }, extra) => attempt(async () => {
1511
+ const id = toId(teamId);
1512
+ 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);
1513
+ return apiCall(ctx, "DELETE", `/v5/teams/${id}`);
1514
+ }));
1515
+ server.registerTool("team_code_create", {
1516
+ title: "Create a team join code",
1517
+ description: "Create an access code athletes use to self-join a team (POST /v5/teams/{teamId}/teamCodes). `type` defaults to 2, the standard join code.",
1518
+ inputSchema: {
1519
+ teamId: idParam,
1520
+ type: z.number().int().optional()
1521
+ },
1522
+ annotations: ADDITIVE
1523
+ }, ({ teamId, type }) => apiCall(ctx, "POST", `/v5/teams/${toId(teamId)}/teamCodes`, { body: { type: type ?? 2 } }));
1524
+ server.registerTool("team_code_delete", {
1525
+ title: "Delete a team join code",
1526
+ description: "Delete a team access code by its id (DELETE /v5/teamCodes/{codeId}). Athletes can no longer use it to join. Requires confirmation (elicitation, or confirm:true).",
1527
+ inputSchema: {
1528
+ codeId: idParam,
1529
+ confirm: z.boolean().optional()
1530
+ },
1531
+ annotations: DESTRUCTIVE
1532
+ }, ({ codeId, confirm }, extra) => attempt(async () => {
1533
+ const id = toId(codeId);
1534
+ if (!await confirmGate(server, extra.requestId, `Delete team join code ${id}? Athletes can no longer use it to join.`, confirm)) return errorResult(NOT_CONFIRMED);
1535
+ return apiCall(ctx, "DELETE", `/v5/teamCodes/${id}`);
1536
+ }));
1537
+ }
1538
+ //#endregion
1539
+ //#region ../core/src/tools/analytics.ts
1540
+ const METRIC_KEYS = [
1541
+ "readiness-team",
1542
+ "readiness-athlete",
1543
+ "lift-1rm-history",
1544
+ "training-summary-athlete",
1545
+ "compliance-team",
1546
+ "lift-progress-team",
1547
+ "working-max-history"
1548
+ ];
1549
+ const METRICS = {
1550
+ "readiness-team": {
1551
+ path: "/v5/analytics/readiness/teams",
1552
+ scope: "team",
1553
+ inputs: ["date"],
1554
+ requires: ["date"]
1555
+ },
1556
+ "readiness-athlete": {
1557
+ path: "/v5/analytics/readiness/users",
1558
+ scope: "user",
1559
+ inputs: ["dateStart", "dateEnd"],
1560
+ requires: ["dateStart", "dateEnd"]
1561
+ },
1562
+ "lift-1rm-history": {
1563
+ path: "/v5/analytics/lift-one-rep-max-history/users",
1564
+ scope: "user",
1565
+ inputs: [
1566
+ "dateStart",
1567
+ "dateEnd",
1568
+ "exerciseId",
1569
+ "useMetric"
1570
+ ],
1571
+ requires: [
1572
+ "dateStart",
1573
+ "dateEnd",
1574
+ "exerciseId"
1575
+ ]
1576
+ },
1577
+ "training-summary-athlete": {
1578
+ path: "/v5/analytics/training-summary/users",
1579
+ scope: "user",
1580
+ inputs: ["dateStart", "dateEnd"],
1581
+ requires: ["dateStart", "dateEnd"]
1582
+ },
1583
+ "compliance-team": {
1584
+ path: "/v5/analytics/compliance",
1585
+ scope: "team",
1586
+ inputs: ["dateStart", "dateEnd"],
1587
+ requires: ["dateStart", "dateEnd"]
1588
+ },
1589
+ "lift-progress-team": {
1590
+ path: "/v5/analytics/lift-progress/teams",
1591
+ scope: "team",
1592
+ inputs: [
1593
+ "exerciseId",
1594
+ "dateStart",
1595
+ "dateEnd"
1596
+ ],
1597
+ requires: [
1598
+ "exerciseId",
1599
+ "dateStart",
1600
+ "dateEnd"
1601
+ ]
1602
+ },
1603
+ "working-max-history": {
1604
+ path: "/v5/analytics/working-max-history/users",
1605
+ scope: "user",
1606
+ inputs: [
1607
+ "exerciseId",
1608
+ "dateStart",
1609
+ "dateEnd",
1610
+ "useMetric"
1611
+ ],
1612
+ requires: ["exerciseId"]
1613
+ }
1614
+ };
1615
+ const BODY_KEY = {
1616
+ date: "date",
1617
+ dateStart: "date_start",
1618
+ dateEnd: "date_end",
1619
+ exerciseId: "exercise_id",
1620
+ useMetric: "use_metric"
1621
+ };
1622
+ /** Analytics report pulls. Read-only despite the POST verb, so ungated. */
1623
+ function registerAnalyticsTools(server, ctx) {
1624
+ server.registerTool("analytics_query", {
1625
+ title: "Pull an analytics report",
1626
+ description: "Read a TrainHeroic analytics report. `metric` picks the report (run analytics_categories for the catalog). Team metrics (readiness-team, compliance-team, lift-progress-team) need teamId; athlete metrics need userIds. readiness-team takes a single `date`; every other metric takes dateStart/dateEnd. lift-1rm-history, lift-progress-team, and working-max-history also need exerciseId. All dates are YYYY-MM-DD.",
1627
+ inputSchema: {
1628
+ metric: z.enum(METRIC_KEYS),
1629
+ teamId: idParam.optional(),
1630
+ userIds: z.array(idParam).optional(),
1631
+ exerciseId: idParam.optional(),
1632
+ date: z.string().optional(),
1633
+ dateStart: z.string().optional(),
1634
+ dateEnd: z.string().optional(),
1635
+ useMetric: z.boolean().optional()
1636
+ },
1637
+ annotations: READ
1638
+ }, async ({ metric, teamId, userIds, exerciseId, date, dateStart, dateEnd, useMetric }) => {
1639
+ const spec = METRICS[metric];
1640
+ const inputs = {
1641
+ date,
1642
+ dateStart,
1643
+ dateEnd,
1644
+ exerciseId,
1645
+ useMetric
1646
+ };
1647
+ const body = {};
1648
+ if (spec.scope === "team") {
1649
+ if (teamId === void 0) return errorResult(`${metric} needs teamId.`);
1650
+ body.teamId = toId(teamId);
1651
+ } else {
1652
+ if (userIds === void 0 || userIds.length === 0) return errorResult(`${metric} needs userIds (one or more athlete ids).`);
1653
+ body.user_ids = userIds.map((u) => String(toId(u)));
1654
+ }
1655
+ const missing = spec.requires.filter((k) => inputs[k] === void 0);
1656
+ if (missing.length > 0) return errorResult(`${metric} also needs: ${missing.join(", ")}.`);
1657
+ for (const k of spec.inputs) {
1658
+ const v = inputs[k];
1659
+ if (v === void 0) continue;
1660
+ body[BODY_KEY[k]] = k === "exerciseId" ? String(toId(v)) : v;
1661
+ }
1662
+ return apiCall(ctx, "POST", spec.path, { body }, "Narrow with a tighter date range or fewer athletes.");
1663
+ });
1664
+ }
1665
+ //#endregion
1666
+ //#region ../core/src/tools/exercises.ts
1667
+ /**
1668
+ * Exercise library tools over the ExerciseIndex — a D1 mirror on the hosted server, an
1669
+ * on-disk/in-memory cache locally. The descriptions stay at the interface level so they
1670
+ * read correctly on both backends.
1671
+ */
1672
+ function registerExerciseTools(server, ctx) {
1673
+ const index = ctx.index;
1674
+ server.registerTool("exercise_resolve", {
1675
+ title: "Resolve exercise name",
1676
+ description: "Map a name to an exercise id via the local mirror. 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.",
1677
+ inputSchema: { name: z.string().min(1) },
1678
+ annotations: READ
1679
+ }, ({ name }) => attempt(async () => jsonResult(await index.resolve(name))));
1680
+ server.registerTool("exercise_search", {
1681
+ title: "Search exercises",
1682
+ description: "Ranked fuzzy search over exercise titles. Returns candidates with units.",
1683
+ inputSchema: {
1684
+ query: z.string().min(1),
1685
+ limit: z.number().int().positive().max(100).optional()
1686
+ },
1687
+ annotations: READ
1688
+ }, ({ query, limit }) => attempt(async () => jsonResult(await index.search(query, limit ?? 20))));
1689
+ server.registerTool("exercise_get", {
1690
+ title: "Get exercise",
1691
+ description: "Full exercise object (with units) by id.",
1692
+ inputSchema: { id: idParam },
1693
+ annotations: READ
1694
+ }, ({ id }) => attempt(async () => {
1695
+ const ex = await index.get(toId(id));
1696
+ return ex ? jsonResult(ex) : errorResult(`No exercise with id ${toId(id)}.`);
1697
+ }));
1698
+ server.registerTool("exercise_sync", {
1699
+ title: "Sync exercise library",
1700
+ description: "Refresh the cached exercise index from TrainHeroic.",
1701
+ inputSchema: { force: z.boolean().optional() },
1702
+ annotations: SYNC
1703
+ }, ({ force }) => attempt(async () => {
1704
+ if (force ?? false) return jsonResult(await index.refresh());
1705
+ await index.ensureFresh();
1706
+ return jsonResult(await index.stats());
1707
+ }));
1708
+ server.registerTool("exercise_create", {
1709
+ title: "Create custom exercise",
1710
+ 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}.",
1711
+ inputSchema: { exercise: exerciseCreateSchema },
1712
+ annotations: {
1713
+ readOnlyHint: false,
1714
+ destructiveHint: false,
1715
+ openWorldHint: true
1716
+ }
1717
+ }, ({ exercise }) => attempt(async () => jsonResult(await index.create(exercise))));
1718
+ server.registerTool("exercise_forget", {
1719
+ title: "Forget exercise (cache only)",
1720
+ description: "Remove an exercise from the local mirror only. Run after deleting it via the API.",
1721
+ inputSchema: { id: idParam },
1722
+ annotations: {
1723
+ readOnlyHint: false,
1724
+ idempotentHint: true,
1725
+ openWorldHint: false
1726
+ }
1727
+ }, ({ id }) => attempt(async () => {
1728
+ await index.recordDelete(toId(id));
1729
+ return jsonResult({ forgotten: toId(id) });
1730
+ }));
1731
+ server.registerTool("store_stats", {
1732
+ title: "Exercise index stats",
1733
+ description: "Row counts and sync state for the cached exercise index.",
1734
+ inputSchema: {},
1735
+ annotations: READ
1736
+ }, () => attempt(async () => jsonResult(await index.stats())));
1737
+ }
1738
+ //#endregion
1329
1739
  //#region ../core/src/tools/workout.ts
1330
- /** Workout building, read-back, publishing, and removal. */
1331
- function registerWorkoutTools(server, ctx) {
1740
+ /** Build a draft, read it back, and publish it. */
1741
+ function registerBuild(server, ctx) {
1332
1742
  server.registerTool("workout_build", {
1333
1743
  title: "Build a workout session (draft)",
1334
1744
  description: "Build an UNPUBLISHED session from a spec (program -> session -> blocks -> exercises). Two exercises in one block become a superset. 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. Review, then workout_publish.",
@@ -1401,6 +1811,9 @@ function registerWorkoutTools(server, ctx) {
1401
1811
  readback: await readSession(ctx.client, programId, parseWorkoutDate(date), pwId)
1402
1812
  });
1403
1813
  }));
1814
+ }
1815
+ /** Calendar lifecycle for an existing session: remove, unpublish, copy, save to library. */
1816
+ function registerLifecycle(server, ctx) {
1404
1817
  server.registerTool("session_remove", {
1405
1818
  title: "Remove a session",
1406
1819
  description: "Delete a session from the live calendar (also the way to replace a date: remove then build). Hard to undo. Requires confirmation (elicitation, or confirm:true).",
@@ -1419,6 +1832,66 @@ function registerWorkoutTools(server, ctx) {
1419
1832
  await removeSession(ctx.client, programId, pwId);
1420
1833
  return jsonResult({ removed: pwId });
1421
1834
  }));
1835
+ server.registerTool("session_unpublish", {
1836
+ title: "Unpublish a session",
1837
+ description: "Unpublish a previously published session (POST .../programWorkout/unPublish/{pwId}). It is no longer athlete-facing. Requires confirmation (elicitation, or confirm:true).",
1838
+ inputSchema: {
1839
+ pwId: z.number(),
1840
+ confirm: z.boolean().optional()
1841
+ },
1842
+ annotations: {
1843
+ readOnlyHint: false,
1844
+ destructiveHint: true,
1845
+ openWorldHint: true
1846
+ }
1847
+ }, ({ pwId, confirm }, extra) => attempt(async () => {
1848
+ if (!await confirmGate(server, extra.requestId, `Unpublish session ${pwId}? Athletes will no longer see it.`, confirm)) return errorResult(NOT_CONFIRMED);
1849
+ return apiCall(ctx, "POST", `/2.0/coach/calendar/programWorkout/unPublish/${pwId}`);
1850
+ }));
1851
+ server.registerTool("session_copy", {
1852
+ title: "Copy a session to a date",
1853
+ description: "Copy/repeat a session to a target date on a program (POST .../copyProgramWorkout). toDate is YYYY-M-D. Creates a new session; review and publish it separately.",
1854
+ inputSchema: {
1855
+ toProgramId: z.number(),
1856
+ pwId: z.number(),
1857
+ toDate: z.string()
1858
+ },
1859
+ annotations: {
1860
+ readOnlyHint: false,
1861
+ destructiveHint: false,
1862
+ openWorldHint: true
1863
+ }
1864
+ }, ({ toProgramId, pwId, toDate }) => attempt(async () => {
1865
+ const [year, month, day] = parseWorkoutDate(toDate);
1866
+ const dayOfWeek = new Date(Date.UTC(year, month - 1, day)).getUTCDay();
1867
+ return apiCall(ctx, "POST", "/2.0/coach/calendar/copyProgramWorkout", { body: {
1868
+ toProgramId,
1869
+ pwId,
1870
+ toDate: {
1871
+ date: `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`,
1872
+ day,
1873
+ month,
1874
+ year,
1875
+ dayOfWeek,
1876
+ isToday: false
1877
+ }
1878
+ } });
1879
+ }));
1880
+ server.registerTool("session_save_as_template", {
1881
+ title: "Save a session to the library",
1882
+ description: "Save an existing session as a reusable template in the session library (POST .../programWorkout/saveWorkoutAsTemplate/{workoutId}). Pass the workout_id.",
1883
+ inputSchema: { workoutId: z.number() },
1884
+ annotations: {
1885
+ readOnlyHint: false,
1886
+ destructiveHint: false,
1887
+ openWorldHint: true
1888
+ }
1889
+ }, ({ workoutId }) => apiCall(ctx, "POST", `/2.0/coach/calendar/programWorkout/saveWorkoutAsTemplate/${workoutId}`));
1890
+ }
1891
+ /** Workout building, read-back, publishing, and the session calendar lifecycle. */
1892
+ function registerWorkoutTools(server, ctx) {
1893
+ registerBuild(server, ctx);
1894
+ registerLifecycle(server, ctx);
1422
1895
  }
1423
1896
  //#endregion
1424
1897
  //#region ../core/src/tools/messaging.ts
@@ -1540,10 +2013,12 @@ async function main() {
1540
2013
  };
1541
2014
  const server = new McpServer({
1542
2015
  name: "trainheroic-local",
1543
- version: "0.1.0"
2016
+ version: "0.2.0"
1544
2017
  });
1545
2018
  registerReadTools(server, ctx);
1546
- registerRawTools(server, ctx);
2019
+ registerAthleteTools(server, ctx);
2020
+ registerTeamTools(server, ctx);
2021
+ registerAnalyticsTools(server, ctx);
1547
2022
  registerExerciseTools(server, ctx);
1548
2023
  registerWorkoutTools(server, ctx);
1549
2024
  registerMessagingTools(server, ctx);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/coach-mcp",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -21,8 +21,8 @@
21
21
  "dependencies": {
22
22
  "@modelcontextprotocol/sdk": "^1.29.0",
23
23
  "zod": "^4.4.3",
24
- "@trainheroic-unofficial/js": "0.2.0",
25
- "@trainheroic-unofficial/core": "0.2.0"
24
+ "@trainheroic-unofficial/core": "0.4.0",
25
+ "@trainheroic-unofficial/js": "0.4.0"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.0.0",