@trainheroic-unofficial/coach-mcp 0.6.0 → 0.6.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 +192 -124
  2. package/package.json +3 -3
package/dist/server.mjs CHANGED
@@ -464,125 +464,6 @@ async function confirmGate(server, requestId, message, confirmArg) {
464
464
  */
465
465
  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.";
466
466
  //#endregion
467
- //#region ../core/src/tools/reads.ts
468
- function enc(value) {
469
- return encodeURIComponent(String(value));
470
- }
471
- /** No-argument GET endpoints, registered from a table to keep the wiring compact. */
472
- const SIMPLE_GETS = [
473
- {
474
- name: "whoami",
475
- title: "Who am I",
476
- description: "The authenticated TrainHeroic coach profile (id, org_id, name, roles, trial days).",
477
- path: "/user/simple"
478
- },
479
- {
480
- name: "head_coach",
481
- title: "Head coach / org",
482
- description: "Org, license, and trial status for the head coach account.",
483
- path: "/v5/headCoach"
484
- },
485
- {
486
- name: "list_programs",
487
- title: "List programs",
488
- description: "Coach programs (standalone). Team group-programs come from list_teams.",
489
- path: "/1.0/coach/programs"
490
- },
491
- {
492
- name: "notifications",
493
- title: "Notification counts",
494
- description: "Unread counts including countMessagingNotViewed (cheap 'anything new?' poll).",
495
- path: "/v5/notifications/counts"
496
- },
497
- {
498
- name: "analytics_categories",
499
- title: "Analytics categories",
500
- description: "Lists available analytics types. Pull a report with analytics_query (pick the matching metric).",
501
- path: "/v5/analytics"
502
- }
503
- ];
504
- /** Roster-level reads: the fixed GETs plus the filterable athlete and team lists. */
505
- function registerRosterReads(server, ctx) {
506
- for (const t of SIMPLE_GETS) server.registerTool(t.name, {
507
- title: t.title,
508
- description: t.description,
509
- inputSchema: {},
510
- annotations: READ
511
- }, () => apiCall(ctx, "GET", t.path));
512
- server.registerTool("list_athletes", {
513
- title: "List athletes",
514
- description: "Athletes visible to this coach. Optional q (case-insensitive substring filter over each athlete record) and limit, applied client-side, to keep large rosters small.",
515
- inputSchema: {
516
- q: z.string().optional(),
517
- limit: z.number().int().positive().max(500).optional()
518
- },
519
- annotations: READ
520
- }, ({ q, limit }) => attempt(async () => {
521
- const res = await ctx.client.request("GET", "/v5/athletes");
522
- if (!res.ok) {
523
- const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
524
- throw new Error(`TrainHeroic API error (HTTP ${res.status}): ${detail}`);
525
- }
526
- if (!Array.isArray(res.data)) return jsonResult(res.data);
527
- let rows = res.data;
528
- if (q !== void 0) {
529
- const needle = q.toLowerCase();
530
- rows = rows.filter((row) => JSON.stringify(row).toLowerCase().includes(needle));
531
- }
532
- const total = rows.length;
533
- if (limit !== void 0 && rows.length > limit) return jsonResult({
534
- items: rows.slice(0, limit),
535
- returned: limit,
536
- total,
537
- note: "Limited client-side. Raise limit or narrow with q for the rest."
538
- });
539
- return jsonResult(rows, { hint: "Filter with q (name/email substring) or cap with limit to shrink this list." });
540
- }));
541
- server.registerTool("list_teams", {
542
- title: "List teams",
543
- description: "Coach teams. Optional pagination and search.",
544
- inputSchema: {
545
- page: z.number().int().positive().optional(),
546
- pageSize: z.number().int().positive().optional(),
547
- q: z.string().optional()
548
- },
549
- annotations: READ
550
- }, ({ page, pageSize, q }) => {
551
- const qs = new URLSearchParams();
552
- if (page !== void 0) qs.set("page", String(page));
553
- if (pageSize !== void 0) qs.set("pageSize", String(pageSize));
554
- if (q !== void 0) qs.set("q", q);
555
- const query = qs.toString();
556
- return apiCall(ctx, "GET", `/1.0/coach/teams${query ? `?${query}` : ""}`);
557
- });
558
- }
559
- /** Reads scoped to a single entity (team, program, athlete) plus the activity feed. */
560
- function registerEntityReads(server, ctx) {
561
- server.registerTool("get_team", {
562
- title: "Get team",
563
- description: "Full team object by team id.",
564
- inputSchema: { teamId: idParam },
565
- annotations: READ
566
- }, ({ teamId }) => apiCall(ctx, "GET", `/v5/teams/${enc(teamId)}`));
567
- server.registerTool("list_team_codes", {
568
- title: "List team access codes",
569
- description: "Join/access codes for a team.",
570
- inputSchema: { teamId: idParam },
571
- annotations: READ
572
- }, ({ teamId }) => apiCall(ctx, "GET", `/v5/teams/${enc(teamId)}/teamCodes`));
573
- server.registerTool("get_program", {
574
- title: "Get program detail",
575
- description: "Full nested program structure (blocks + sessions) live from the API, by program id.",
576
- inputSchema: { programId: idParam },
577
- annotations: READ
578
- }, ({ 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."));
579
- }
580
- /** Read-only coach/athlete queries. Exercise lookups live in the exercise store tools. */
581
- function registerReadTools(server, ctx) {
582
- registerRosterReads(server, ctx);
583
- registerEntityReads(server, ctx);
584
- }
585
- //#endregion
586
467
  //#region ../js/src/auth.ts
587
468
  const AUTH_URL = "https://apis.trainheroic.com/auth";
588
469
  /**
@@ -839,6 +720,36 @@ function rankSearch(rows, query, limit) {
839
720
  }).sort((a, b) => b.score - a.score).slice(0, limit).map((s) => s.row);
840
721
  }
841
722
  //#endregion
723
+ //#region ../js/src/athlete.ts
724
+ async function getJson(client, path, label) {
725
+ const res = await client.request("GET", path);
726
+ if (!res.ok) throw new Error(`${label} failed (HTTP ${res.status}).`);
727
+ return res.data;
728
+ }
729
+ function fetchExerciseHistoryDetail(client, exerciseId, userId) {
730
+ return getJson(client, `/v5/exercises/${exerciseId}/history?userId=${userId}`, "athlete exercise history");
731
+ }
732
+ /** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
733
+ function presentExerciseHistory(detail) {
734
+ return {
735
+ liftPRs: (detail.liftPRs ?? []).map((p) => ({
736
+ description: p.description ?? null,
737
+ reps: p.reps ?? null,
738
+ weight: p.weight ?? null,
739
+ date: p.dateCompleted ?? null
740
+ })),
741
+ sessions: (detail.history ?? []).map((h) => ({
742
+ date: h.dateCompleted,
743
+ abr: h.abr ?? null,
744
+ estimated1RM: h.bestEstimated1RM ?? null,
745
+ sets: (h.sets ?? []).map((s) => ({
746
+ setNumber: s.setNumber,
747
+ value: s.formattedValue ?? null
748
+ }))
749
+ }))
750
+ };
751
+ }
752
+ //#endregion
842
753
  //#region ../js/src/workout-encode.ts
843
754
  const LEADERBOARD_TYPE = {
844
755
  completion: 0,
@@ -1405,6 +1316,163 @@ var ExerciseLibrary = class {
1405
1316
  }
1406
1317
  };
1407
1318
  //#endregion
1319
+ //#region ../core/src/history.ts
1320
+ /**
1321
+ * Trim a presented exercise history's session time-series to an inclusive YYYY-MM-DD window.
1322
+ * The `liftPRs` board stays all-time (PRs are not a windowed concept). Dates compare as their
1323
+ * first 10 chars so both "YYYY-MM-DD" and "YYYY-MM-DDThh:mm" values filter correctly. Shared by
1324
+ * the athlete's own history tool and the coach's per-roster-athlete history tool.
1325
+ */
1326
+ function historyInRange(presented, since, until) {
1327
+ if (since === void 0 && until === void 0) return presented;
1328
+ const sessions = presented.sessions.filter((s) => {
1329
+ const d = (s.date ?? "").slice(0, 10);
1330
+ if (since !== void 0 && d < since) return false;
1331
+ if (until !== void 0 && d > until) return false;
1332
+ return true;
1333
+ });
1334
+ return {
1335
+ ...presented,
1336
+ sessions
1337
+ };
1338
+ }
1339
+ //#endregion
1340
+ //#region ../core/src/tools/reads.ts
1341
+ const ATHLETE_LIFT_HISTORY_DESC = "A roster athlete's lift history for ONE exercise: the all-time PR board (liftPRs — each entry carries its rep-max label, weight, and the date it was set) plus the dated session series (sets, estimated 1RM). This is the coach-side way to answer 'show me <athlete>'s PRs / how is <athlete>'s squat trending' — pass athleteId from list_athletes and exerciseId from exercise_resolve. There is no cross-exercise PR summary, so query each lift you care about (squat, bench, deadlift, …) and an empty result just means the athlete has not logged that lift. liftPRs stay all-time; pass since/until (YYYY-MM-DD, inclusive) to window the session series. raw:true returns the untouched API object.";
1342
+ function enc(value) {
1343
+ return encodeURIComponent(String(value));
1344
+ }
1345
+ /** No-argument GET endpoints, registered from a table to keep the wiring compact. */
1346
+ const SIMPLE_GETS = [
1347
+ {
1348
+ name: "whoami",
1349
+ title: "Who am I",
1350
+ description: "The authenticated TrainHeroic coach profile (id, org_id, name, roles, trial days).",
1351
+ path: "/user/simple"
1352
+ },
1353
+ {
1354
+ name: "head_coach",
1355
+ title: "Head coach / org",
1356
+ description: "Org, license, and trial status for the head coach account.",
1357
+ path: "/v5/headCoach"
1358
+ },
1359
+ {
1360
+ name: "list_programs",
1361
+ title: "List programs",
1362
+ description: "Coach programs (standalone only). This is often empty even for an active coach, because most programming lives as a team's group-program: if it returns [], call list_teams and read each team's group_program — do not conclude the coach has no programs.",
1363
+ path: "/1.0/coach/programs"
1364
+ },
1365
+ {
1366
+ name: "notifications",
1367
+ title: "Notification counts",
1368
+ description: "Unread counts including countMessagingNotViewed (cheap 'anything new?' poll).",
1369
+ path: "/v5/notifications/counts"
1370
+ },
1371
+ {
1372
+ name: "analytics_categories",
1373
+ title: "Analytics categories",
1374
+ description: "TrainHeroic's raw analytics catalog. Its keys are the API's own names and do NOT match analytics_query's `metric` values — choose the metric straight from analytics_query's (self-describing) enum instead; you rarely need this tool.",
1375
+ path: "/v5/analytics"
1376
+ }
1377
+ ];
1378
+ /** Roster-level reads: the fixed GETs plus the filterable athlete and team lists. */
1379
+ function registerRosterReads(server, ctx) {
1380
+ for (const t of SIMPLE_GETS) server.registerTool(t.name, {
1381
+ title: t.title,
1382
+ description: t.description,
1383
+ inputSchema: {},
1384
+ annotations: READ
1385
+ }, () => apiCall(ctx, "GET", t.path));
1386
+ server.registerTool("list_athletes", {
1387
+ title: "List athletes",
1388
+ description: "Every athlete on this coach's org roster, across all teams (not scoped to one team, and demo/placeholder athletes are included). `daysSinceLastLogin` is app-login recency, not training activity — an athlete can have logged in today yet have no logged sessions; null means no login on record. There is no per-athlete team field here, so to attribute athletes to a team use the team's roster. Optional q (case-insensitive substring filter over each athlete record) and limit, applied client-side, to keep large rosters small.",
1389
+ inputSchema: {
1390
+ q: z.string().optional(),
1391
+ limit: z.number().int().positive().max(500).optional()
1392
+ },
1393
+ annotations: READ
1394
+ }, ({ q, limit }) => attempt(async () => {
1395
+ const res = await ctx.client.request("GET", "/v5/athletes");
1396
+ if (!res.ok) {
1397
+ const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
1398
+ throw new Error(`TrainHeroic API error (HTTP ${res.status}): ${detail}`);
1399
+ }
1400
+ if (!Array.isArray(res.data)) return jsonResult(res.data);
1401
+ let rows = res.data;
1402
+ if (q !== void 0) {
1403
+ const needle = q.toLowerCase();
1404
+ rows = rows.filter((row) => JSON.stringify(row).toLowerCase().includes(needle));
1405
+ }
1406
+ const total = rows.length;
1407
+ if (limit !== void 0 && rows.length > limit) return jsonResult({
1408
+ items: rows.slice(0, limit),
1409
+ returned: limit,
1410
+ total,
1411
+ note: "Limited client-side. Raise limit or narrow with q for the rest."
1412
+ });
1413
+ return jsonResult(rows, { hint: "Filter with q (name/email substring) or cap with limit to shrink this list." });
1414
+ }));
1415
+ server.registerTool("list_teams", {
1416
+ title: "List teams",
1417
+ description: "Coach teams. The headcount fields are easy to misread: member_count and athlete_count are enrolled-athlete counts and are commonly 0 (a coach-built team with no enrolled members), while athleteIds typically holds just the owner's id, NOT the full roster. For who is actually on the roster use list_athletes (org-wide). Each team's group_program id is the team's programming. Optional pagination and search.",
1418
+ inputSchema: {
1419
+ page: z.number().int().positive().optional(),
1420
+ pageSize: z.number().int().positive().optional(),
1421
+ q: z.string().optional()
1422
+ },
1423
+ annotations: READ
1424
+ }, ({ page, pageSize, q }) => {
1425
+ const qs = new URLSearchParams();
1426
+ if (page !== void 0) qs.set("page", String(page));
1427
+ if (pageSize !== void 0) qs.set("pageSize", String(pageSize));
1428
+ if (q !== void 0) qs.set("q", q);
1429
+ const query = qs.toString();
1430
+ return apiCall(ctx, "GET", `/1.0/coach/teams${query ? `?${query}` : ""}`);
1431
+ });
1432
+ }
1433
+ /** Reads scoped to a single entity (team, program, athlete) plus the activity feed. */
1434
+ function registerEntityReads(server, ctx) {
1435
+ server.registerTool("get_team", {
1436
+ title: "Get team",
1437
+ description: "Full team object by team id.",
1438
+ inputSchema: { teamId: idParam },
1439
+ annotations: READ
1440
+ }, ({ teamId }) => apiCall(ctx, "GET", `/v5/teams/${enc(teamId)}`));
1441
+ server.registerTool("list_team_codes", {
1442
+ title: "List team access codes",
1443
+ description: "Join/access codes for a team.",
1444
+ inputSchema: { teamId: idParam },
1445
+ annotations: READ
1446
+ }, ({ teamId }) => apiCall(ctx, "GET", `/v5/teams/${enc(teamId)}/teamCodes`));
1447
+ server.registerTool("athlete_lift_history", {
1448
+ title: "Athlete lift history + PRs (roster)",
1449
+ description: ATHLETE_LIFT_HISTORY_DESC,
1450
+ inputSchema: {
1451
+ athleteId: idParam,
1452
+ exerciseId: idParam,
1453
+ raw: z.boolean().optional(),
1454
+ since: dateString.optional(),
1455
+ until: dateString.optional()
1456
+ },
1457
+ annotations: READ
1458
+ }, ({ athleteId, exerciseId, raw, since, until }) => attempt(async () => {
1459
+ const detail = await fetchExerciseHistoryDetail(ctx.client, toId(exerciseId), toId(athleteId));
1460
+ if (raw === true) return jsonResult(detail);
1461
+ return jsonResult(historyInRange(presentExerciseHistory(detail), since, until));
1462
+ }));
1463
+ server.registerTool("get_program", {
1464
+ title: "Get program detail",
1465
+ description: "Full nested program structure (blocks + sessions) live from the API, by program id.",
1466
+ inputSchema: { programId: idParam },
1467
+ annotations: READ
1468
+ }, ({ 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."));
1469
+ }
1470
+ /** Read-only coach/athlete queries. Exercise lookups live in the exercise store tools. */
1471
+ function registerReadTools(server, ctx) {
1472
+ registerRosterReads(server, ctx);
1473
+ registerEntityReads(server, ctx);
1474
+ }
1475
+ //#endregion
1408
1476
  //#region ../core/src/tools/athletes.ts
1409
1477
  const DEFAULT_INVITE_MESSAGE = "Follow these steps and you'll be set up and ready to go!";
1410
1478
  /** Normalize one-or-many emails into a deduped, trimmed list. */
@@ -1634,7 +1702,7 @@ const BODY_KEY = {
1634
1702
  function registerAnalyticsTools(server, ctx) {
1635
1703
  server.registerTool("analytics_query", {
1636
1704
  title: "Pull an analytics report",
1637
- 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.",
1705
+ description: "Read a TrainHeroic analytics report. The `metric` enum below IS the catalog — pick from it directly (analytics_categories lists the API's raw category names, which do NOT match these keys; you rarely need it). Team metrics (readiness-team, compliance-team, lift-progress-team) need teamId; athlete metrics (readiness-athlete, training-summary-athlete, lift-1rm-history, working-max-history) need userIds — get those from list_athletes. userIds takes MANY athletes in ONE call (pass the whole roster's ids at once); the report comes back with a row per athlete, so do not loop one id per call. For team-wide training volume there is no team summary metric: pass every athlete's userId to training-summary-athlete in a single call and the rows cover the team. An athlete with no logged sessions in range simply returns no rows (not an error). 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.",
1638
1706
  inputSchema: {
1639
1707
  metric: z.enum(METRIC_KEYS),
1640
1708
  teamId: idParam.optional(),
@@ -1684,13 +1752,13 @@ function registerExerciseTools(server, ctx) {
1684
1752
  const index = ctx.index;
1685
1753
  server.registerTool("exercise_resolve", {
1686
1754
  title: "Resolve exercise name",
1687
- 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.",
1755
+ description: "Map a name to an exercise id via the local mirror. Prefer this over exercise_search when you want a single authoritative id for a known name. Returns the match plus ranked candidates; when ambiguous, match is null and you should pick from candidates. Each result's `units` array lists the fixed measurement units by entry slot; they are fixed per exercise — check them before prescribing. `can_edit` is 1 only for the coach's own custom exercises and 0 for built-in library exercises.",
1688
1756
  inputSchema: { name: z.string().min(1) },
1689
1757
  annotations: READ
1690
1758
  }, ({ name }) => attempt(async () => jsonResult(await index.resolve(name))));
1691
1759
  server.registerTool("exercise_search", {
1692
1760
  title: "Search exercises",
1693
- description: "Ranked fuzzy search over exercise titles. Returns candidates with units.",
1761
+ description: "Ranked fuzzy search over exercise titles. Returns candidates with units. Each result's `can_edit` flag marks ownership: 1 = the coach's own custom exercise, 0 = a built-in library exercise — filter on it to answer 'do I have a custom exercise for X'. When you want one definitive id for a known name, use exercise_resolve instead.",
1694
1762
  inputSchema: {
1695
1763
  query: z.string().min(1),
1696
1764
  limit: z.number().int().positive().max(100).optional()
@@ -1923,7 +1991,7 @@ function registerReads(server, ctx) {
1923
1991
  }));
1924
1992
  server.registerTool("messaging_read", {
1925
1993
  title: "Read messages (live)",
1926
- description: "Recent comments in a stream, live from the API (the stream is fetched whole, then trimmed to `limit`).",
1994
+ description: "Recent comments in a stream, live from the API (the stream is fetched whole, then trimmed to `limit`, default 20). Each comment's `isAuthor` is true when the logged-in user sent it — to answer 'did an athlete message me', look for comments with isAuthor:false. Timestamps are Unix seconds. An empty result means the thread has no messages.",
1927
1995
  inputSchema: {
1928
1996
  streamId: idParam,
1929
1997
  limit: z.number().int().positive().max(200).optional()
@@ -2010,7 +2078,7 @@ var JsonFileLibraryCache = class {
2010
2078
  };
2011
2079
  //#endregion
2012
2080
  //#region package.json
2013
- var version = "0.4.1";
2081
+ var version = "0.6.1";
2014
2082
  //#endregion
2015
2083
  //#region src/server.ts
2016
2084
  async function main() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/coach-mcp",
3
- "version": "0.6.0",
3
+ "version": "0.6.1",
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/core": "0.6.0",
25
- "@trainheroic-unofficial/js": "0.6.0"
24
+ "@trainheroic-unofficial/core": "0.6.1",
25
+ "@trainheroic-unofficial/js": "0.6.1"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.0.0",