@trainheroic-unofficial/coach-mcp 0.3.0 → 0.4.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.
- package/dist/server.mjs +654 -507
- 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({
|
|
@@ -414,37 +565,6 @@ function registerEntityReads(server, ctx) {
|
|
|
414
565
|
inputSchema: { programId: idParam },
|
|
415
566
|
annotations: READ
|
|
416
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."));
|
|
417
|
-
server.registerTool("coach_activity_feed", {
|
|
418
|
-
title: "Coach activity feed",
|
|
419
|
-
description: "Recent athlete activity across the roster (GET /v5/coaches/activityFeed): completed workouts, PRs, and posts. Paginate with page/pageSize.",
|
|
420
|
-
inputSchema: {
|
|
421
|
-
page: z.number().int().positive().optional(),
|
|
422
|
-
pageSize: z.number().int().positive().optional()
|
|
423
|
-
},
|
|
424
|
-
annotations: READ
|
|
425
|
-
}, ({ page, pageSize }) => {
|
|
426
|
-
const qs = new URLSearchParams();
|
|
427
|
-
if (page !== void 0) qs.set("page", String(page));
|
|
428
|
-
if (pageSize !== void 0) qs.set("pageSize", String(pageSize));
|
|
429
|
-
const query = qs.toString();
|
|
430
|
-
return apiCall(ctx, "GET", `/v5/coaches/activityFeed${query ? `?${query}` : ""}`);
|
|
431
|
-
});
|
|
432
|
-
server.registerTool("athlete_workouts", {
|
|
433
|
-
title: "Athlete workout history",
|
|
434
|
-
description: "One athlete's workouts with their survey/readiness data (GET /v5/coaches/athletes/{athleteId}/workouts). Bound it with startDate/endDate (YYYY-MM-DD) to keep the response small.",
|
|
435
|
-
inputSchema: {
|
|
436
|
-
athleteId: idParam,
|
|
437
|
-
startDate: z.string().optional(),
|
|
438
|
-
endDate: z.string().optional()
|
|
439
|
-
},
|
|
440
|
-
annotations: READ
|
|
441
|
-
}, ({ athleteId, startDate, endDate }) => {
|
|
442
|
-
const qs = new URLSearchParams();
|
|
443
|
-
if (startDate !== void 0) qs.set("startDate", startDate);
|
|
444
|
-
if (endDate !== void 0) qs.set("endDate", endDate);
|
|
445
|
-
const query = qs.toString();
|
|
446
|
-
return apiCall(ctx, "GET", `/v5/coaches/athletes/${enc(athleteId)}/workouts${query ? `?${query}` : ""}`, void 0, "Narrow the date range to shrink this if it is truncated.");
|
|
447
|
-
});
|
|
448
568
|
}
|
|
449
569
|
/** Read-only coach/athlete queries. Exercise lookups live in the exercise store tools. */
|
|
450
570
|
function registerReadTools(server, ctx) {
|
|
@@ -452,497 +572,182 @@ function registerReadTools(server, ctx) {
|
|
|
452
572
|
registerEntityReads(server, ctx);
|
|
453
573
|
}
|
|
454
574
|
//#endregion
|
|
455
|
-
//#region ../
|
|
456
|
-
const
|
|
457
|
-
/** Normalize one-or-many emails into a deduped, trimmed list. */
|
|
458
|
-
function asEmailList(emails) {
|
|
459
|
-
return [...new Set((Array.isArray(emails) ? emails : [emails]).map((e) => e.trim()).filter((e) => e.length > 0))];
|
|
460
|
-
}
|
|
575
|
+
//#region ../js/src/auth.ts
|
|
576
|
+
const AUTH_URL = "https://apis.trainheroic.com/auth";
|
|
461
577
|
/**
|
|
462
|
-
*
|
|
463
|
-
*
|
|
464
|
-
*
|
|
465
|
-
*
|
|
466
|
-
* (POST /v5/athletes/inviteToTeam). Both act on the live account, so the invite is gated.
|
|
578
|
+
* Authenticate against TrainHeroic. Returns the session bundle, or null on bad
|
|
579
|
+
* credentials. TrainHeroic returns only { id, scope, role, session_id } (verified in
|
|
580
|
+
* the Phase 0 spike: no refresh_token, no api_token, no TTL). The 48-char session_id
|
|
581
|
+
* is sent as the `session-token` header and works against both API hosts.
|
|
467
582
|
*/
|
|
468
|
-
function
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
emails: z.union([z.string(), z.array(z.string()).min(1)]),
|
|
475
|
-
message: z.string().optional(),
|
|
476
|
-
confirm: z.boolean().optional()
|
|
583
|
+
async function loginTrainHeroic(email, password) {
|
|
584
|
+
const res = await fetch(AUTH_URL, {
|
|
585
|
+
method: "POST",
|
|
586
|
+
headers: {
|
|
587
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
588
|
+
accept: "application/json"
|
|
477
589
|
},
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
590
|
+
body: new URLSearchParams({
|
|
591
|
+
email,
|
|
592
|
+
password
|
|
593
|
+
}).toString()
|
|
594
|
+
});
|
|
595
|
+
if (!res.ok) return null;
|
|
596
|
+
const data = await res.json().catch(() => null);
|
|
597
|
+
if (!data || typeof data.id !== "number" || !data.session_id) return null;
|
|
598
|
+
return {
|
|
599
|
+
thUserId: data.id,
|
|
600
|
+
sessionId: data.session_id,
|
|
601
|
+
scope: data.scope ?? "",
|
|
602
|
+
role: data.role ?? ""
|
|
603
|
+
};
|
|
604
|
+
}
|
|
605
|
+
//#endregion
|
|
606
|
+
//#region ../js/src/client.ts
|
|
607
|
+
const COACH_BASE = "https://api.trainheroic.com";
|
|
608
|
+
const APIS_BASE = "https://apis.trainheroic.com";
|
|
609
|
+
var TrainHeroicAuthError = class extends Error {
|
|
610
|
+
name = "TrainHeroicAuthError";
|
|
611
|
+
};
|
|
612
|
+
/**
|
|
613
|
+
* Authenticated TrainHeroic API client. Holds the coach credentials (from the grant's
|
|
614
|
+
* encrypted props) and a lazily-acquired session token cached in memory for the life
|
|
615
|
+
* of the Durable Object instance. On a 401/403 it re-logs in once and retries, since
|
|
616
|
+
* TrainHeroic has no refresh token and sessions expire after ~1-2h.
|
|
617
|
+
*/
|
|
618
|
+
var TrainHeroicClient = class {
|
|
619
|
+
#email;
|
|
620
|
+
#password;
|
|
621
|
+
#sessionId;
|
|
622
|
+
#loginInFlight = null;
|
|
623
|
+
constructor(email, password, sessionId = null) {
|
|
624
|
+
this.#email = email;
|
|
625
|
+
this.#password = password;
|
|
626
|
+
this.#sessionId = sessionId;
|
|
627
|
+
}
|
|
628
|
+
get sessionId() {
|
|
629
|
+
return this.#sessionId;
|
|
630
|
+
}
|
|
631
|
+
async #ensureSession() {
|
|
632
|
+
if (this.#sessionId) return this.#sessionId;
|
|
633
|
+
this.#loginInFlight ??= this.#login();
|
|
634
|
+
try {
|
|
635
|
+
return await this.#loginInFlight;
|
|
636
|
+
} finally {
|
|
637
|
+
this.#loginInFlight = null;
|
|
488
638
|
}
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
const
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
} }
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
639
|
+
}
|
|
640
|
+
async #login() {
|
|
641
|
+
const session = await loginTrainHeroic(this.#email, this.#password);
|
|
642
|
+
if (!session) throw new TrainHeroicAuthError("TrainHeroic login failed");
|
|
643
|
+
this.#sessionId = session.sessionId;
|
|
644
|
+
return this.#sessionId;
|
|
645
|
+
}
|
|
646
|
+
async request(method, path, options = {}) {
|
|
647
|
+
const url = `${options.base === "apis" ? APIS_BASE : COACH_BASE}/${path.replace(/^\//, "")}`;
|
|
648
|
+
let session = await this.#ensureSession();
|
|
649
|
+
let res = await this.#send(method, url, session, options.body);
|
|
650
|
+
if (res.status === 401 || res.status === 403) {
|
|
651
|
+
if (this.#sessionId === session) this.#sessionId = null;
|
|
652
|
+
session = await this.#ensureSession();
|
|
653
|
+
res = await this.#send(method, url, session, options.body);
|
|
501
654
|
}
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
}
|
|
507
|
-
|
|
508
|
-
server.registerTool("athlete_archive", {
|
|
509
|
-
title: "Archive athletes",
|
|
510
|
-
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).",
|
|
511
|
-
inputSchema: {
|
|
512
|
-
athleteIds: z.array(idParam).min(1),
|
|
513
|
-
confirm: z.boolean().optional()
|
|
514
|
-
},
|
|
515
|
-
annotations: DESTRUCTIVE
|
|
516
|
-
}, ({ athleteIds, confirm }, extra) => attempt(async () => {
|
|
517
|
-
const ids = athleteIds.map(toId);
|
|
518
|
-
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);
|
|
519
|
-
return apiCall(ctx, "PUT", "/v5/athletes/archive", { body: { athleteIds: ids } });
|
|
520
|
-
}));
|
|
521
|
-
server.registerTool("athlete_restore", {
|
|
522
|
-
title: "Restore athletes",
|
|
523
|
-
description: "Restore previously archived athletes to the active roster (PUT /v5/athletes/restore).",
|
|
524
|
-
inputSchema: { athleteIds: z.array(idParam).min(1) },
|
|
525
|
-
annotations: {
|
|
526
|
-
readOnlyHint: false,
|
|
527
|
-
idempotentHint: true,
|
|
528
|
-
destructiveHint: false,
|
|
529
|
-
openWorldHint: true
|
|
655
|
+
const text = await res.text();
|
|
656
|
+
let data = text;
|
|
657
|
+
if (text.length > 0) try {
|
|
658
|
+
data = JSON.parse(text);
|
|
659
|
+
} catch {
|
|
660
|
+
data = text;
|
|
530
661
|
}
|
|
531
|
-
|
|
662
|
+
return {
|
|
663
|
+
status: res.status,
|
|
664
|
+
ok: res.ok,
|
|
665
|
+
data
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
#send(method, url, session, body) {
|
|
669
|
+
const upper = method.toUpperCase();
|
|
670
|
+
const headers = {
|
|
671
|
+
accept: "application/json",
|
|
672
|
+
"session-token": session
|
|
673
|
+
};
|
|
674
|
+
const init = {
|
|
675
|
+
method: upper,
|
|
676
|
+
headers
|
|
677
|
+
};
|
|
678
|
+
if (body !== void 0 && upper !== "GET" && upper !== "DELETE") {
|
|
679
|
+
headers["content-type"] = "application/json";
|
|
680
|
+
init.body = JSON.stringify(body);
|
|
681
|
+
}
|
|
682
|
+
return fetch(url, init);
|
|
683
|
+
}
|
|
684
|
+
};
|
|
685
|
+
//#endregion
|
|
686
|
+
//#region ../js/src/response-check.ts
|
|
687
|
+
/**
|
|
688
|
+
* Validate an API response against its (loose) expected shape and warn once on drift.
|
|
689
|
+
* Never throws: callers keep working via defensive coercion. This only surfaces a signal
|
|
690
|
+
* when TrainHeroic renames or drops a field we read.
|
|
691
|
+
*/
|
|
692
|
+
function checkResponse(schema, data, label) {
|
|
693
|
+
const result = schema.safeParse(data);
|
|
694
|
+
if (result.success) return;
|
|
695
|
+
const issue = result.error.issues[0];
|
|
696
|
+
const where = issue && issue.path.length > 0 ? issue.path.join(".") : "(root)";
|
|
697
|
+
console.warn(`[trainheroic] response drift in ${label} at ${where}: ${issue?.message ?? "shape mismatch"}`);
|
|
532
698
|
}
|
|
533
699
|
//#endregion
|
|
534
|
-
//#region ../
|
|
535
|
-
const ADDITIVE = {
|
|
536
|
-
readOnlyHint: false,
|
|
537
|
-
destructiveHint: false,
|
|
538
|
-
openWorldHint: true
|
|
539
|
-
};
|
|
700
|
+
//#region ../js/src/exercise-util.ts
|
|
540
701
|
/**
|
|
541
|
-
*
|
|
542
|
-
*
|
|
702
|
+
* Display labels for TrainHeroic parameter types. The unit is FIXED PER EXERCISE
|
|
703
|
+
* (the API forces param_1_type/param_2_type back to the library default on save), so
|
|
704
|
+
* resolve/search surface it to stop callers picking, say, the miles "Run" for a
|
|
705
|
+
* metric workout. Keep in sync with the workout builder's unit table.
|
|
543
706
|
*/
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
}, ({ teamId, title }) => apiCall(ctx, "PUT", `/v5/teams/${toId(teamId)}`, { body: { title } }));
|
|
560
|
-
server.registerTool("team_delete", {
|
|
561
|
-
title: "Delete a team",
|
|
562
|
-
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).",
|
|
563
|
-
inputSchema: {
|
|
564
|
-
teamId: idParam,
|
|
565
|
-
confirm: z.boolean().optional()
|
|
566
|
-
},
|
|
567
|
-
annotations: DESTRUCTIVE
|
|
568
|
-
}, ({ teamId, confirm }, extra) => attempt(async () => {
|
|
569
|
-
const id = toId(teamId);
|
|
570
|
-
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);
|
|
571
|
-
return apiCall(ctx, "DELETE", `/v5/teams/${id}`);
|
|
572
|
-
}));
|
|
573
|
-
server.registerTool("team_code_create", {
|
|
574
|
-
title: "Create a team join code",
|
|
575
|
-
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.",
|
|
576
|
-
inputSchema: {
|
|
577
|
-
teamId: idParam,
|
|
578
|
-
type: z.number().int().optional()
|
|
579
|
-
},
|
|
580
|
-
annotations: ADDITIVE
|
|
581
|
-
}, ({ teamId, type }) => apiCall(ctx, "POST", `/v5/teams/${toId(teamId)}/teamCodes`, { body: { type: type ?? 2 } }));
|
|
582
|
-
server.registerTool("team_code_delete", {
|
|
583
|
-
title: "Delete a team join code",
|
|
584
|
-
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).",
|
|
585
|
-
inputSchema: {
|
|
586
|
-
codeId: idParam,
|
|
587
|
-
confirm: z.boolean().optional()
|
|
588
|
-
},
|
|
589
|
-
annotations: DESTRUCTIVE
|
|
590
|
-
}, ({ codeId, confirm }, extra) => attempt(async () => {
|
|
591
|
-
const id = toId(codeId);
|
|
592
|
-
if (!await confirmGate(server, extra.requestId, `Delete team join code ${id}? Athletes can no longer use it to join.`, confirm)) return errorResult(NOT_CONFIRMED);
|
|
593
|
-
return apiCall(ctx, "DELETE", `/v5/teamCodes/${id}`);
|
|
594
|
-
}));
|
|
595
|
-
}
|
|
596
|
-
//#endregion
|
|
597
|
-
//#region ../core/src/tools/analytics.ts
|
|
598
|
-
const METRIC_KEYS = [
|
|
599
|
-
"readiness-team",
|
|
600
|
-
"readiness-athlete",
|
|
601
|
-
"lift-1rm-history",
|
|
602
|
-
"training-summary-athlete",
|
|
603
|
-
"training-summary-team",
|
|
604
|
-
"compliance-team",
|
|
605
|
-
"lift-progress-team",
|
|
606
|
-
"working-max-history"
|
|
607
|
-
];
|
|
608
|
-
const METRICS = {
|
|
609
|
-
"readiness-team": {
|
|
610
|
-
path: "/v5/analytics/readiness/teams",
|
|
611
|
-
scope: "team",
|
|
612
|
-
fields: ["date"]
|
|
613
|
-
},
|
|
614
|
-
"readiness-athlete": {
|
|
615
|
-
path: "/v5/analytics/readiness/users",
|
|
616
|
-
scope: "user",
|
|
617
|
-
fields: ["date"]
|
|
618
|
-
},
|
|
619
|
-
"lift-1rm-history": {
|
|
620
|
-
path: "/v5/analytics/lift-one-rep-max-history/users",
|
|
621
|
-
scope: "user",
|
|
622
|
-
fields: [
|
|
623
|
-
"date_start",
|
|
624
|
-
"date_end",
|
|
625
|
-
"exercise_id",
|
|
626
|
-
"use_metric"
|
|
627
|
-
]
|
|
628
|
-
},
|
|
629
|
-
"training-summary-athlete": {
|
|
630
|
-
path: "/v5/analytics/training-summary/users",
|
|
631
|
-
scope: "user",
|
|
632
|
-
fields: ["date_start", "date_end"]
|
|
633
|
-
},
|
|
634
|
-
"training-summary-team": {
|
|
635
|
-
path: "/v5/analytics/training-summary/teams",
|
|
636
|
-
scope: "team",
|
|
637
|
-
fields: ["date_start", "date_end"]
|
|
638
|
-
},
|
|
639
|
-
"compliance-team": {
|
|
640
|
-
path: "/v5/analytics/compliance",
|
|
641
|
-
scope: "team",
|
|
642
|
-
fields: ["date_start", "date_end"]
|
|
643
|
-
},
|
|
644
|
-
"lift-progress-team": {
|
|
645
|
-
path: "/v5/analytics/lift-progress/teams",
|
|
646
|
-
scope: "team",
|
|
647
|
-
fields: [
|
|
648
|
-
"exercise_id",
|
|
649
|
-
"date_start",
|
|
650
|
-
"date_end"
|
|
651
|
-
]
|
|
652
|
-
},
|
|
653
|
-
"working-max-history": {
|
|
654
|
-
path: "/v5/analytics/working-max-history/users",
|
|
655
|
-
scope: "user",
|
|
656
|
-
fields: ["date_start", "date_end"]
|
|
657
|
-
}
|
|
707
|
+
const PARAM_UNIT = {
|
|
708
|
+
0: null,
|
|
709
|
+
1: "lb",
|
|
710
|
+
2: "%max",
|
|
711
|
+
3: "reps",
|
|
712
|
+
4: "sec",
|
|
713
|
+
5: "yd",
|
|
714
|
+
6: "m",
|
|
715
|
+
7: "in",
|
|
716
|
+
10: "mi",
|
|
717
|
+
11: "ft",
|
|
718
|
+
12: "in",
|
|
719
|
+
13: "bpm",
|
|
720
|
+
14: "RPE",
|
|
721
|
+
18: "sec"
|
|
658
722
|
};
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
userIds: z.array(idParam).optional(),
|
|
668
|
-
exerciseId: idParam.optional(),
|
|
669
|
-
date: z.string().optional(),
|
|
670
|
-
dateStart: z.string().optional(),
|
|
671
|
-
dateEnd: z.string().optional(),
|
|
672
|
-
useMetric: z.boolean().optional()
|
|
673
|
-
},
|
|
674
|
-
annotations: READ
|
|
675
|
-
}, async ({ metric, teamId, userIds, exerciseId, date, dateStart, dateEnd, useMetric }) => {
|
|
676
|
-
const spec = METRICS[metric];
|
|
677
|
-
const body = {};
|
|
678
|
-
if (spec.scope === "team") {
|
|
679
|
-
if (teamId === void 0) return errorResult(`${metric} needs teamId.`);
|
|
680
|
-
body.teamId = toId(teamId);
|
|
681
|
-
} else {
|
|
682
|
-
if (userIds === void 0 || userIds.length === 0) return errorResult(`${metric} needs userIds (one or more athlete ids).`);
|
|
683
|
-
body.user_ids = userIds.map((u) => String(toId(u)));
|
|
684
|
-
}
|
|
685
|
-
const provided = {
|
|
686
|
-
date,
|
|
687
|
-
date_start: dateStart,
|
|
688
|
-
date_end: dateEnd,
|
|
689
|
-
exercise_id: exerciseId === void 0 ? void 0 : String(toId(exerciseId)),
|
|
690
|
-
use_metric: useMetric
|
|
691
|
-
};
|
|
692
|
-
for (const field of spec.fields) if (provided[field] !== void 0) body[field] = provided[field];
|
|
693
|
-
return apiCall(ctx, "POST", spec.path, { body }, "Narrow with a tighter date range or fewer athletes.");
|
|
694
|
-
});
|
|
723
|
+
function coerceInt(value) {
|
|
724
|
+
if (typeof value === "boolean") return value ? 1 : 0;
|
|
725
|
+
if (typeof value === "number") return Number.isFinite(value) ? Math.trunc(value) : null;
|
|
726
|
+
if (typeof value === "string" && value.trim() !== "") {
|
|
727
|
+
const n = Number(value);
|
|
728
|
+
return Number.isFinite(n) ? Math.trunc(n) : null;
|
|
729
|
+
}
|
|
730
|
+
return null;
|
|
695
731
|
}
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
* on-disk/in-memory cache locally. The descriptions stay at the interface level so they
|
|
701
|
-
* read correctly on both backends.
|
|
702
|
-
*/
|
|
703
|
-
function registerExerciseTools(server, ctx) {
|
|
704
|
-
const index = ctx.index;
|
|
705
|
-
server.registerTool("exercise_resolve", {
|
|
706
|
-
title: "Resolve exercise name",
|
|
707
|
-
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.",
|
|
708
|
-
inputSchema: { name: z.string().min(1) },
|
|
709
|
-
annotations: READ
|
|
710
|
-
}, ({ name }) => attempt(async () => jsonResult(await index.resolve(name))));
|
|
711
|
-
server.registerTool("exercise_search", {
|
|
712
|
-
title: "Search exercises",
|
|
713
|
-
description: "Ranked fuzzy search over exercise titles. Returns candidates with units.",
|
|
714
|
-
inputSchema: {
|
|
715
|
-
query: z.string().min(1),
|
|
716
|
-
limit: z.number().int().positive().max(100).optional()
|
|
717
|
-
},
|
|
718
|
-
annotations: READ
|
|
719
|
-
}, ({ query, limit }) => attempt(async () => jsonResult(await index.search(query, limit ?? 20))));
|
|
720
|
-
server.registerTool("exercise_get", {
|
|
721
|
-
title: "Get exercise",
|
|
722
|
-
description: "Full exercise object (with units) by id.",
|
|
723
|
-
inputSchema: { id: idParam },
|
|
724
|
-
annotations: READ
|
|
725
|
-
}, ({ id }) => attempt(async () => {
|
|
726
|
-
const ex = await index.get(toId(id));
|
|
727
|
-
return ex ? jsonResult(ex) : errorResult(`No exercise with id ${toId(id)}.`);
|
|
728
|
-
}));
|
|
729
|
-
server.registerTool("exercise_sync", {
|
|
730
|
-
title: "Sync exercise library",
|
|
731
|
-
description: "Refresh the cached exercise index from TrainHeroic.",
|
|
732
|
-
inputSchema: { force: z.boolean().optional() },
|
|
733
|
-
annotations: SYNC
|
|
734
|
-
}, ({ force }) => attempt(async () => {
|
|
735
|
-
if (force ?? false) return jsonResult(await index.refresh());
|
|
736
|
-
await index.ensureFresh();
|
|
737
|
-
return jsonResult(await index.stats());
|
|
738
|
-
}));
|
|
739
|
-
server.registerTool("exercise_create", {
|
|
740
|
-
title: "Create custom exercise",
|
|
741
|
-
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}.",
|
|
742
|
-
inputSchema: { exercise: exerciseCreateSchema },
|
|
743
|
-
annotations: {
|
|
744
|
-
readOnlyHint: false,
|
|
745
|
-
destructiveHint: false,
|
|
746
|
-
openWorldHint: true
|
|
747
|
-
}
|
|
748
|
-
}, ({ exercise }) => attempt(async () => jsonResult(await index.create(exercise))));
|
|
749
|
-
server.registerTool("exercise_forget", {
|
|
750
|
-
title: "Forget exercise (cache only)",
|
|
751
|
-
description: "Remove an exercise from the local mirror only. Run after deleting it via the API.",
|
|
752
|
-
inputSchema: { id: idParam },
|
|
753
|
-
annotations: {
|
|
754
|
-
readOnlyHint: false,
|
|
755
|
-
idempotentHint: true,
|
|
756
|
-
openWorldHint: false
|
|
757
|
-
}
|
|
758
|
-
}, ({ id }) => attempt(async () => {
|
|
759
|
-
await index.recordDelete(toId(id));
|
|
760
|
-
return jsonResult({ forgotten: toId(id) });
|
|
761
|
-
}));
|
|
762
|
-
server.registerTool("store_stats", {
|
|
763
|
-
title: "Exercise index stats",
|
|
764
|
-
description: "Row counts and sync state for the cached exercise index.",
|
|
765
|
-
inputSchema: {},
|
|
766
|
-
annotations: READ
|
|
767
|
-
}, () => attempt(async () => jsonResult(await index.stats())));
|
|
732
|
+
function unitLabel(paramType) {
|
|
733
|
+
const t = coerceInt(paramType);
|
|
734
|
+
if (t === null) return null;
|
|
735
|
+
return PARAM_UNIT[t] ?? null;
|
|
768
736
|
}
|
|
769
|
-
//#endregion
|
|
770
|
-
//#region ../js/src/auth.ts
|
|
771
|
-
const AUTH_URL = "https://apis.trainheroic.com/auth";
|
|
772
737
|
/**
|
|
773
|
-
*
|
|
774
|
-
*
|
|
775
|
-
*
|
|
776
|
-
* is sent as the `session-token` header and works against both API hosts.
|
|
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.
|
|
777
741
|
*/
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
},
|
|
785
|
-
body: new URLSearchParams({
|
|
786
|
-
email,
|
|
787
|
-
password
|
|
788
|
-
}).toString()
|
|
789
|
-
});
|
|
790
|
-
if (!res.ok) return null;
|
|
791
|
-
const data = await res.json().catch(() => null);
|
|
792
|
-
if (!data || typeof data.id !== "number" || !data.session_id) return null;
|
|
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. */
|
|
746
|
+
function withUnits(row) {
|
|
747
|
+
const { param_1_type, param_2_type, ...rest } = row;
|
|
793
748
|
return {
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
scope: data.scope ?? "",
|
|
797
|
-
role: data.role ?? ""
|
|
798
|
-
};
|
|
799
|
-
}
|
|
800
|
-
//#endregion
|
|
801
|
-
//#region ../js/src/client.ts
|
|
802
|
-
const COACH_BASE = "https://api.trainheroic.com";
|
|
803
|
-
const APIS_BASE = "https://apis.trainheroic.com";
|
|
804
|
-
var TrainHeroicAuthError = class extends Error {
|
|
805
|
-
name = "TrainHeroicAuthError";
|
|
806
|
-
};
|
|
807
|
-
/**
|
|
808
|
-
* Authenticated TrainHeroic API client. Holds the coach credentials (from the grant's
|
|
809
|
-
* encrypted props) and a lazily-acquired session token cached in memory for the life
|
|
810
|
-
* of the Durable Object instance. On a 401/403 it re-logs in once and retries, since
|
|
811
|
-
* TrainHeroic has no refresh token and sessions expire after ~1-2h.
|
|
812
|
-
*/
|
|
813
|
-
var TrainHeroicClient = class {
|
|
814
|
-
#email;
|
|
815
|
-
#password;
|
|
816
|
-
#sessionId;
|
|
817
|
-
#loginInFlight = null;
|
|
818
|
-
constructor(email, password, sessionId = null) {
|
|
819
|
-
this.#email = email;
|
|
820
|
-
this.#password = password;
|
|
821
|
-
this.#sessionId = sessionId;
|
|
822
|
-
}
|
|
823
|
-
get sessionId() {
|
|
824
|
-
return this.#sessionId;
|
|
825
|
-
}
|
|
826
|
-
async #ensureSession() {
|
|
827
|
-
if (this.#sessionId) return this.#sessionId;
|
|
828
|
-
this.#loginInFlight ??= this.#login();
|
|
829
|
-
try {
|
|
830
|
-
return await this.#loginInFlight;
|
|
831
|
-
} finally {
|
|
832
|
-
this.#loginInFlight = null;
|
|
833
|
-
}
|
|
834
|
-
}
|
|
835
|
-
async #login() {
|
|
836
|
-
const session = await loginTrainHeroic(this.#email, this.#password);
|
|
837
|
-
if (!session) throw new TrainHeroicAuthError("TrainHeroic login failed");
|
|
838
|
-
this.#sessionId = session.sessionId;
|
|
839
|
-
return this.#sessionId;
|
|
840
|
-
}
|
|
841
|
-
async request(method, path, options = {}) {
|
|
842
|
-
const url = `${options.base === "apis" ? APIS_BASE : COACH_BASE}/${path.replace(/^\//, "")}`;
|
|
843
|
-
let session = await this.#ensureSession();
|
|
844
|
-
let res = await this.#send(method, url, session, options.body);
|
|
845
|
-
if (res.status === 401 || res.status === 403) {
|
|
846
|
-
if (this.#sessionId === session) this.#sessionId = null;
|
|
847
|
-
session = await this.#ensureSession();
|
|
848
|
-
res = await this.#send(method, url, session, options.body);
|
|
849
|
-
}
|
|
850
|
-
const text = await res.text();
|
|
851
|
-
let data = text;
|
|
852
|
-
if (text.length > 0) try {
|
|
853
|
-
data = JSON.parse(text);
|
|
854
|
-
} catch {
|
|
855
|
-
data = text;
|
|
856
|
-
}
|
|
857
|
-
return {
|
|
858
|
-
status: res.status,
|
|
859
|
-
ok: res.ok,
|
|
860
|
-
data
|
|
861
|
-
};
|
|
862
|
-
}
|
|
863
|
-
#send(method, url, session, body) {
|
|
864
|
-
const upper = method.toUpperCase();
|
|
865
|
-
const headers = {
|
|
866
|
-
accept: "application/json",
|
|
867
|
-
"session-token": session
|
|
868
|
-
};
|
|
869
|
-
const init = {
|
|
870
|
-
method: upper,
|
|
871
|
-
headers
|
|
872
|
-
};
|
|
873
|
-
if (body !== void 0 && upper !== "GET" && upper !== "DELETE") {
|
|
874
|
-
headers["content-type"] = "application/json";
|
|
875
|
-
init.body = JSON.stringify(body);
|
|
876
|
-
}
|
|
877
|
-
return fetch(url, init);
|
|
878
|
-
}
|
|
879
|
-
};
|
|
880
|
-
//#endregion
|
|
881
|
-
//#region ../js/src/response-check.ts
|
|
882
|
-
/**
|
|
883
|
-
* Validate an API response against its (loose) expected shape and warn once on drift.
|
|
884
|
-
* Never throws: callers keep working via defensive coercion. This only surfaces a signal
|
|
885
|
-
* when TrainHeroic renames or drops a field we read.
|
|
886
|
-
*/
|
|
887
|
-
function checkResponse(schema, data, label) {
|
|
888
|
-
const result = schema.safeParse(data);
|
|
889
|
-
if (result.success) return;
|
|
890
|
-
const issue = result.error.issues[0];
|
|
891
|
-
const where = issue && issue.path.length > 0 ? issue.path.join(".") : "(root)";
|
|
892
|
-
console.warn(`[trainheroic] response drift in ${label} at ${where}: ${issue?.message ?? "shape mismatch"}`);
|
|
893
|
-
}
|
|
894
|
-
//#endregion
|
|
895
|
-
//#region ../js/src/exercise-util.ts
|
|
896
|
-
/**
|
|
897
|
-
* Display labels for TrainHeroic parameter types. The unit is FIXED PER EXERCISE
|
|
898
|
-
* (the API forces param_1_type/param_2_type back to the library default on save), so
|
|
899
|
-
* resolve/search surface it to stop callers picking, say, the miles "Run" for a
|
|
900
|
-
* metric workout. Keep in sync with the workout builder's unit table.
|
|
901
|
-
*/
|
|
902
|
-
const PARAM_UNIT = {
|
|
903
|
-
0: null,
|
|
904
|
-
1: "lb",
|
|
905
|
-
2: "%max",
|
|
906
|
-
3: "reps",
|
|
907
|
-
4: "sec",
|
|
908
|
-
5: "yd",
|
|
909
|
-
6: "m",
|
|
910
|
-
7: "in",
|
|
911
|
-
10: "mi",
|
|
912
|
-
11: "ft",
|
|
913
|
-
12: "in",
|
|
914
|
-
13: "bpm",
|
|
915
|
-
14: "RPE",
|
|
916
|
-
18: "sec"
|
|
917
|
-
};
|
|
918
|
-
function coerceInt(value) {
|
|
919
|
-
if (typeof value === "boolean") return value ? 1 : 0;
|
|
920
|
-
if (typeof value === "number") return Number.isFinite(value) ? Math.trunc(value) : null;
|
|
921
|
-
if (typeof value === "string" && value.trim() !== "") {
|
|
922
|
-
const n = Number(value);
|
|
923
|
-
return Number.isFinite(n) ? Math.trunc(n) : null;
|
|
924
|
-
}
|
|
925
|
-
return null;
|
|
926
|
-
}
|
|
927
|
-
function unitLabel(paramType) {
|
|
928
|
-
const t = coerceInt(paramType);
|
|
929
|
-
if (t === null) return null;
|
|
930
|
-
return PARAM_UNIT[t] ?? null;
|
|
931
|
-
}
|
|
932
|
-
/**
|
|
933
|
-
* Fixed measurement units for an exercise, ordered by entry slot (param 1, then param 2).
|
|
934
|
-
* Positional, not semantic: some exercises reverse the slots, so the array is not labelled
|
|
935
|
-
* by role. A null entry is an unset slot.
|
|
936
|
-
*/
|
|
937
|
-
function exerciseUnits(param1, param2) {
|
|
938
|
-
return [unitLabel(param1), unitLabel(param2)];
|
|
939
|
-
}
|
|
940
|
-
/** Present a row for display: drop the raw param-type codes, surface units positionally. */
|
|
941
|
-
function withUnits(row) {
|
|
942
|
-
const { param_1_type, param_2_type, ...rest } = row;
|
|
943
|
-
return {
|
|
944
|
-
...rest,
|
|
945
|
-
units: exerciseUnits(param_1_type, param_2_type)
|
|
749
|
+
...rest,
|
|
750
|
+
units: exerciseUnits(param_1_type, param_2_type)
|
|
946
751
|
};
|
|
947
752
|
}
|
|
948
753
|
/**
|
|
@@ -1015,7 +820,7 @@ function rankSearch(rows, query, limit) {
|
|
|
1015
820
|
if (title.startsWith(q)) score += 100;
|
|
1016
821
|
for (const tok of tokens) if (title.includes(tok)) score += 10;
|
|
1017
822
|
score -= title.length * .05;
|
|
1018
|
-
if (row.can_edit === 0) score += 1;
|
|
823
|
+
if ((row.can_edit ?? 0) === 0) score += 1;
|
|
1019
824
|
return {
|
|
1020
825
|
row,
|
|
1021
826
|
score
|
|
@@ -1589,6 +1394,348 @@ var ExerciseLibrary = class {
|
|
|
1589
1394
|
}
|
|
1590
1395
|
};
|
|
1591
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
|
|
1592
1739
|
//#region ../core/src/tools/workout.ts
|
|
1593
1740
|
/** Build a draft, read it back, and publish it. */
|
|
1594
1741
|
function registerBuild(server, ctx) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trainheroic-unofficial/coach-mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.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.
|
|
25
|
-
"@trainheroic-unofficial/js": "0.
|
|
24
|
+
"@trainheroic-unofficial/core": "0.4.1",
|
|
25
|
+
"@trainheroic-unofficial/js": "0.4.1"
|
|
26
26
|
},
|
|
27
27
|
"devDependencies": {
|
|
28
28
|
"@types/node": "^26.0.0",
|