@almostjacked/hevy-mcp-core 0.1.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.
- package/LICENSE +21 -0
- package/dist/exercises.d.ts +2 -0
- package/dist/exercises.js +40 -0
- package/dist/hevy-client.d.ts +117 -0
- package/dist/hevy-client.js +124 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -0
- package/dist/routine-builder.d.ts +25 -0
- package/dist/routine-builder.js +42 -0
- package/dist/summary.d.ts +21 -0
- package/dist/summary.js +55 -0
- package/dist/tools.d.ts +11 -0
- package/dist/tools.js +216 -0
- package/dist/units.d.ts +11 -0
- package/dist/units.js +19 -0
- package/dist/workouts.d.ts +48 -0
- package/dist/workouts.js +124 -0
- package/package.json +39 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 AJ Wallace
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
function bigrams(s) {
|
|
2
|
+
const m = new Map();
|
|
3
|
+
const clean = s.toLowerCase().replace(/[^a-z0-9 ]/g, "");
|
|
4
|
+
for (let i = 0; i < clean.length - 1; i++) {
|
|
5
|
+
const g = clean.slice(i, i + 2);
|
|
6
|
+
m.set(g, (m.get(g) ?? 0) + 1);
|
|
7
|
+
}
|
|
8
|
+
return m;
|
|
9
|
+
}
|
|
10
|
+
/** Sørensen–Dice similarity over character bigrams, 0..1 */
|
|
11
|
+
function similarity(a, b) {
|
|
12
|
+
const ga = bigrams(a);
|
|
13
|
+
const gb = bigrams(b);
|
|
14
|
+
let overlap = 0;
|
|
15
|
+
for (const [g, n] of ga)
|
|
16
|
+
overlap += Math.min(n, gb.get(g) ?? 0);
|
|
17
|
+
const total = [...ga.values()].reduce((s, n) => s + n, 0) + [...gb.values()].reduce((s, n) => s + n, 0);
|
|
18
|
+
return total === 0 ? 0 : (2 * overlap) / total;
|
|
19
|
+
}
|
|
20
|
+
export function searchExercises(query, templates, limit = 10) {
|
|
21
|
+
const q = query.trim().toLowerCase();
|
|
22
|
+
if (!q)
|
|
23
|
+
return [];
|
|
24
|
+
return templates
|
|
25
|
+
.map((t) => {
|
|
26
|
+
const title = t.title.toLowerCase();
|
|
27
|
+
let score;
|
|
28
|
+
if (title === q)
|
|
29
|
+
score = 3;
|
|
30
|
+
else if (title.includes(q) || q.includes(title))
|
|
31
|
+
score = 2 + similarity(q, title);
|
|
32
|
+
else
|
|
33
|
+
score = similarity(q, title);
|
|
34
|
+
return { t, score };
|
|
35
|
+
})
|
|
36
|
+
.filter((x) => x.score >= 0.4)
|
|
37
|
+
.sort((a, b) => b.score - a.score)
|
|
38
|
+
.slice(0, limit)
|
|
39
|
+
.map((x) => x.t);
|
|
40
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
export interface ExerciseTemplate {
|
|
2
|
+
id: string;
|
|
3
|
+
title: string;
|
|
4
|
+
type: string;
|
|
5
|
+
primary_muscle_group: string;
|
|
6
|
+
equipment: string;
|
|
7
|
+
}
|
|
8
|
+
export interface RoutineFolder {
|
|
9
|
+
id: number;
|
|
10
|
+
title: string;
|
|
11
|
+
}
|
|
12
|
+
export interface RoutineSummary {
|
|
13
|
+
id: number;
|
|
14
|
+
title: string;
|
|
15
|
+
folder_id: number | null;
|
|
16
|
+
exercise_count: number;
|
|
17
|
+
}
|
|
18
|
+
export interface RoutineSet {
|
|
19
|
+
type: string;
|
|
20
|
+
weight_kg: number | null;
|
|
21
|
+
reps: number | null;
|
|
22
|
+
distance_meters: number | null;
|
|
23
|
+
duration_seconds: number | null;
|
|
24
|
+
custom_metric: number | null;
|
|
25
|
+
}
|
|
26
|
+
export interface RoutineExercise {
|
|
27
|
+
exercise_template_id: string;
|
|
28
|
+
superset_id: number | null;
|
|
29
|
+
rest_seconds: number | null;
|
|
30
|
+
notes: string;
|
|
31
|
+
sets: RoutineSet[];
|
|
32
|
+
}
|
|
33
|
+
export interface RoutinePayload {
|
|
34
|
+
routine: {
|
|
35
|
+
title: string;
|
|
36
|
+
folder_id: number | null;
|
|
37
|
+
notes: string;
|
|
38
|
+
exercises: RoutineExercise[];
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
export interface WorkoutSet {
|
|
42
|
+
index: number;
|
|
43
|
+
type: string;
|
|
44
|
+
weight_kg: number | null;
|
|
45
|
+
reps: number | null;
|
|
46
|
+
distance_meters: number | null;
|
|
47
|
+
duration_seconds: number | null;
|
|
48
|
+
rpe: number | null;
|
|
49
|
+
custom_metric: number | null;
|
|
50
|
+
}
|
|
51
|
+
export interface WorkoutExercise {
|
|
52
|
+
index: number;
|
|
53
|
+
title: string;
|
|
54
|
+
exercise_template_id: string;
|
|
55
|
+
superset_id: number | null;
|
|
56
|
+
notes: string;
|
|
57
|
+
sets: WorkoutSet[];
|
|
58
|
+
}
|
|
59
|
+
export interface Workout {
|
|
60
|
+
id: string;
|
|
61
|
+
title: string;
|
|
62
|
+
start_time: string;
|
|
63
|
+
end_time: string;
|
|
64
|
+
exercises: WorkoutExercise[];
|
|
65
|
+
}
|
|
66
|
+
export interface WorkoutsPage {
|
|
67
|
+
page: number;
|
|
68
|
+
page_count: number;
|
|
69
|
+
workouts: Workout[];
|
|
70
|
+
}
|
|
71
|
+
export interface ExerciseHistoryRow {
|
|
72
|
+
workout_id: string;
|
|
73
|
+
workout_title: string;
|
|
74
|
+
workout_start_time: string;
|
|
75
|
+
workout_end_time: string;
|
|
76
|
+
exercise_template_id: string;
|
|
77
|
+
weight_kg: number | null;
|
|
78
|
+
reps: number | null;
|
|
79
|
+
distance_meters: number | null;
|
|
80
|
+
duration_seconds: number | null;
|
|
81
|
+
rpe: number | null;
|
|
82
|
+
custom_metric: number | null;
|
|
83
|
+
set_type: string;
|
|
84
|
+
}
|
|
85
|
+
export type RoutineUpdatePayload = {
|
|
86
|
+
routine: Omit<RoutinePayload["routine"], "folder_id">;
|
|
87
|
+
};
|
|
88
|
+
export declare class HevyApiError extends Error {
|
|
89
|
+
status: number;
|
|
90
|
+
body: string;
|
|
91
|
+
path: string;
|
|
92
|
+
constructor(status: number, body: string, path: string);
|
|
93
|
+
}
|
|
94
|
+
export declare class HevyClient {
|
|
95
|
+
private apiKey;
|
|
96
|
+
private fetchFn;
|
|
97
|
+
private maxRequestsPerMinute;
|
|
98
|
+
private timestamps;
|
|
99
|
+
constructor(apiKey: string, fetchFn?: typeof fetch, maxRequestsPerMinute?: number);
|
|
100
|
+
private request;
|
|
101
|
+
private paged;
|
|
102
|
+
validateKey(): Promise<boolean>;
|
|
103
|
+
fetchAllExerciseTemplates(): Promise<ExerciseTemplate[]>;
|
|
104
|
+
listRoutineFolders(): Promise<RoutineFolder[]>;
|
|
105
|
+
createRoutineFolder(title: string): Promise<RoutineFolder>;
|
|
106
|
+
listRoutines(query?: string): Promise<RoutineSummary[]>;
|
|
107
|
+
createRoutine(payload: RoutinePayload): Promise<unknown>;
|
|
108
|
+
getWorkoutsPage(page?: number, pageSize?: number): Promise<WorkoutsPage>;
|
|
109
|
+
getWorkoutCount(): Promise<number>;
|
|
110
|
+
getWorkout(workoutId: string): Promise<Workout>;
|
|
111
|
+
getRoutine(routineId: string | number): Promise<unknown>;
|
|
112
|
+
updateRoutine(routineId: string | number, payload: RoutineUpdatePayload): Promise<unknown>;
|
|
113
|
+
getExerciseHistory(templateId: string, startDate?: string, endDate?: string): Promise<{
|
|
114
|
+
rows: ExerciseHistoryRow[];
|
|
115
|
+
truncated: boolean;
|
|
116
|
+
}>;
|
|
117
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
const BASE = "https://api.hevyapp.com";
|
|
2
|
+
export class HevyApiError extends Error {
|
|
3
|
+
status;
|
|
4
|
+
body;
|
|
5
|
+
path;
|
|
6
|
+
constructor(status, body, path) {
|
|
7
|
+
super(`Hevy API ${status} on ${path}: ${body}`);
|
|
8
|
+
this.status = status;
|
|
9
|
+
this.body = body;
|
|
10
|
+
this.path = path;
|
|
11
|
+
this.name = "HevyApiError";
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
export class HevyClient {
|
|
15
|
+
apiKey;
|
|
16
|
+
fetchFn;
|
|
17
|
+
maxRequestsPerMinute;
|
|
18
|
+
timestamps = [];
|
|
19
|
+
constructor(apiKey, fetchFn = (input, init) => globalThis.fetch(input, init), maxRequestsPerMinute = 30) {
|
|
20
|
+
this.apiKey = apiKey;
|
|
21
|
+
this.fetchFn = fetchFn;
|
|
22
|
+
this.maxRequestsPerMinute = maxRequestsPerMinute;
|
|
23
|
+
}
|
|
24
|
+
async request(method, path, body) {
|
|
25
|
+
const now = Date.now();
|
|
26
|
+
this.timestamps = this.timestamps.filter((t) => now - t < 60_000);
|
|
27
|
+
if (this.timestamps.length >= this.maxRequestsPerMinute) {
|
|
28
|
+
throw new HevyApiError(429, "Client-side rate limit reached; wait a minute before more Hevy calls.", path);
|
|
29
|
+
}
|
|
30
|
+
this.timestamps.push(now);
|
|
31
|
+
const res = await this.fetchFn(BASE + path, {
|
|
32
|
+
method,
|
|
33
|
+
headers: { "api-key": this.apiKey, "Content-Type": "application/json" },
|
|
34
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
35
|
+
});
|
|
36
|
+
const text = await res.text();
|
|
37
|
+
if (!res.ok)
|
|
38
|
+
throw new HevyApiError(res.status, text.slice(0, 500), path);
|
|
39
|
+
return text ? JSON.parse(text) : null;
|
|
40
|
+
}
|
|
41
|
+
async paged(path, pageSize, itemsKey) {
|
|
42
|
+
const all = [];
|
|
43
|
+
let page = 1;
|
|
44
|
+
for (;;) {
|
|
45
|
+
const data = await this.request("GET", `${path}?page=${page}&pageSize=${pageSize}`);
|
|
46
|
+
all.push(...(data[itemsKey] ?? []));
|
|
47
|
+
if (page >= (data.page_count ?? 1))
|
|
48
|
+
break;
|
|
49
|
+
page++;
|
|
50
|
+
}
|
|
51
|
+
return all;
|
|
52
|
+
}
|
|
53
|
+
async validateKey() {
|
|
54
|
+
try {
|
|
55
|
+
await this.request("GET", "/v1/workouts/count");
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
58
|
+
catch (e) {
|
|
59
|
+
if (e instanceof HevyApiError && (e.status === 401 || e.status === 403))
|
|
60
|
+
return false;
|
|
61
|
+
throw e;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
fetchAllExerciseTemplates() {
|
|
65
|
+
return this.paged("/v1/exercise_templates", 100, "exercise_templates");
|
|
66
|
+
}
|
|
67
|
+
listRoutineFolders() {
|
|
68
|
+
return this.paged("/v1/routine_folders", 10, "routine_folders");
|
|
69
|
+
}
|
|
70
|
+
async createRoutineFolder(title) {
|
|
71
|
+
const existing = (await this.listRoutineFolders()).find((f) => f.title === title);
|
|
72
|
+
if (existing)
|
|
73
|
+
return existing;
|
|
74
|
+
const res = await this.request("POST", "/v1/routine_folders", { routine_folder: { title } });
|
|
75
|
+
return res.routine_folder ?? res;
|
|
76
|
+
}
|
|
77
|
+
async listRoutines(query) {
|
|
78
|
+
const raw = await this.paged("/v1/routines", 10, "routines");
|
|
79
|
+
const q = query?.trim().toLowerCase();
|
|
80
|
+
return raw
|
|
81
|
+
.filter((r) => !q || String(r.title ?? "").toLowerCase().includes(q))
|
|
82
|
+
.map((r) => ({
|
|
83
|
+
id: r.id,
|
|
84
|
+
title: r.title,
|
|
85
|
+
folder_id: r.folder_id ?? null,
|
|
86
|
+
exercise_count: (r.exercises ?? []).length,
|
|
87
|
+
}));
|
|
88
|
+
}
|
|
89
|
+
createRoutine(payload) {
|
|
90
|
+
return this.request("POST", "/v1/routines", payload);
|
|
91
|
+
}
|
|
92
|
+
async getWorkoutsPage(page = 1, pageSize = 10) {
|
|
93
|
+
const data = await this.request("GET", `/v1/workouts?page=${page}&pageSize=${pageSize}`);
|
|
94
|
+
return { page: data.page ?? page, page_count: data.page_count ?? 1, workouts: data.workouts ?? [] };
|
|
95
|
+
}
|
|
96
|
+
async getWorkoutCount() {
|
|
97
|
+
const data = await this.request("GET", "/v1/workouts/count");
|
|
98
|
+
return data.workout_count ?? 0;
|
|
99
|
+
}
|
|
100
|
+
async getWorkout(workoutId) {
|
|
101
|
+
const data = await this.request("GET", `/v1/workouts/${encodeURIComponent(workoutId)}`);
|
|
102
|
+
return data.workout ?? data;
|
|
103
|
+
}
|
|
104
|
+
async getRoutine(routineId) {
|
|
105
|
+
const data = await this.request("GET", `/v1/routines/${encodeURIComponent(String(routineId))}`);
|
|
106
|
+
return data.routine ?? data;
|
|
107
|
+
}
|
|
108
|
+
updateRoutine(routineId, payload) {
|
|
109
|
+
return this.request("PUT", `/v1/routines/${encodeURIComponent(String(routineId))}`, payload);
|
|
110
|
+
}
|
|
111
|
+
async getExerciseHistory(templateId, startDate, endDate) {
|
|
112
|
+
const qs = new URLSearchParams();
|
|
113
|
+
if (startDate)
|
|
114
|
+
qs.set("start_date", startDate);
|
|
115
|
+
if (endDate)
|
|
116
|
+
qs.set("end_date", endDate);
|
|
117
|
+
const q = qs.toString();
|
|
118
|
+
const data = await this.request("GET", `/v1/exercise_history/${encodeURIComponent(templateId)}${q ? `?${q}` : ""}`);
|
|
119
|
+
return {
|
|
120
|
+
rows: data.exercise_history ?? [],
|
|
121
|
+
truncated: data.page_count != null && data.page_count > 1,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { createHevyClient, registerTools, keyInvalidMessage, type RegisterOptions } from "./tools.js";
|
|
2
|
+
export { HevyClient, HevyApiError, type ExerciseTemplate } from "./hevy-client.js";
|
|
3
|
+
export { searchExercises } from "./exercises.js";
|
|
4
|
+
export { buildRoutinePayload } from "./routine-builder.js";
|
|
5
|
+
export { summarizeWorkout, groupExerciseHistory, scanWorkouts } from "./workouts.js";
|
|
6
|
+
export { computeTrainingSummary } from "./summary.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { createHevyClient, registerTools, keyInvalidMessage } from "./tools.js";
|
|
2
|
+
export { HevyClient, HevyApiError } from "./hevy-client.js";
|
|
3
|
+
export { searchExercises } from "./exercises.js";
|
|
4
|
+
export { buildRoutinePayload } from "./routine-builder.js";
|
|
5
|
+
export { summarizeWorkout, groupExerciseHistory, scanWorkouts } from "./workouts.js";
|
|
6
|
+
export { computeTrainingSummary } from "./summary.js";
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { RoutinePayload } from "./hevy-client.js";
|
|
2
|
+
export interface SetInput {
|
|
3
|
+
type?: "warmup" | "normal" | "failure" | "dropset";
|
|
4
|
+
weight_kg?: number | null;
|
|
5
|
+
weight_lb?: number | null;
|
|
6
|
+
reps?: number | null;
|
|
7
|
+
rpe?: number | null;
|
|
8
|
+
duration_seconds?: number | null;
|
|
9
|
+
distance_meters?: number | null;
|
|
10
|
+
custom_metric?: number | null;
|
|
11
|
+
}
|
|
12
|
+
export interface ExerciseInput {
|
|
13
|
+
exercise_template_id: string;
|
|
14
|
+
superset_id?: number | null;
|
|
15
|
+
rest_seconds?: number | null;
|
|
16
|
+
notes?: string;
|
|
17
|
+
sets: SetInput[];
|
|
18
|
+
}
|
|
19
|
+
export interface RoutineInput {
|
|
20
|
+
title: string;
|
|
21
|
+
folder_id?: number | null;
|
|
22
|
+
notes?: string;
|
|
23
|
+
exercises: ExerciseInput[];
|
|
24
|
+
}
|
|
25
|
+
export declare function buildRoutinePayload(input: RoutineInput, validTemplateIds: Set<string>): RoutinePayload;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { KG_PER_LB, roundToIncrement } from "./units.js";
|
|
2
|
+
export function buildRoutinePayload(input, validTemplateIds) {
|
|
3
|
+
const unknown = [...new Set(input.exercises.map((e) => e.exercise_template_id).filter((id) => !validTemplateIds.has(id)))];
|
|
4
|
+
if (unknown.length) {
|
|
5
|
+
throw new Error(`Unknown exercise_template_id(s): ${unknown.join(", ")}. ` +
|
|
6
|
+
`Use the search_exercises tool to find valid template ids before creating the routine.`);
|
|
7
|
+
}
|
|
8
|
+
return {
|
|
9
|
+
routine: {
|
|
10
|
+
title: input.title,
|
|
11
|
+
folder_id: input.folder_id ?? null,
|
|
12
|
+
notes: input.notes ?? "",
|
|
13
|
+
exercises: input.exercises.map((e) => {
|
|
14
|
+
// Hevy's routines API rejects "rpe" on sets, so targets go into notes.
|
|
15
|
+
// Strip a prior fold only when re-folding, so echoed updates (no rpe on
|
|
16
|
+
// sets) preserve existing notes instead of wiping the fold.
|
|
17
|
+
let notes = e.notes ?? "";
|
|
18
|
+
const rpes = e.sets.map((s) => s.rpe).filter((r) => r != null);
|
|
19
|
+
if (rpes.length) {
|
|
20
|
+
notes = notes.replace(/\s*Top set @ RPE [0-9/.]+\s*$/, "").trim();
|
|
21
|
+
notes = `${notes} Top set @ RPE ${rpes.join("/")}`.trim();
|
|
22
|
+
}
|
|
23
|
+
return {
|
|
24
|
+
exercise_template_id: e.exercise_template_id,
|
|
25
|
+
superset_id: e.superset_id ?? null,
|
|
26
|
+
rest_seconds: e.rest_seconds ?? null,
|
|
27
|
+
notes,
|
|
28
|
+
sets: e.sets.map((s) => ({
|
|
29
|
+
type: s.type ?? "normal",
|
|
30
|
+
weight_kg: s.weight_kg ??
|
|
31
|
+
// 6dp, not 2: 0.01 kg quantization skews the app's lb display (135 → "134.99").
|
|
32
|
+
(s.weight_lb != null ? Math.round(roundToIncrement(s.weight_lb) * KG_PER_LB * 1e6) / 1e6 : null),
|
|
33
|
+
reps: s.reps ?? null,
|
|
34
|
+
distance_meters: s.distance_meters ?? null,
|
|
35
|
+
duration_seconds: s.duration_seconds ?? null,
|
|
36
|
+
custom_metric: s.custom_metric ?? null,
|
|
37
|
+
})),
|
|
38
|
+
};
|
|
39
|
+
}),
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { Workout } from "./hevy-client.js";
|
|
2
|
+
export interface WeeklyStats {
|
|
3
|
+
week_start: string;
|
|
4
|
+
sessions: number;
|
|
5
|
+
volume_lb: number;
|
|
6
|
+
}
|
|
7
|
+
export interface LiftTrend {
|
|
8
|
+
exercise: string;
|
|
9
|
+
weekly_best_est_1rm_lb: {
|
|
10
|
+
week_start: string;
|
|
11
|
+
est_1rm_lb: number;
|
|
12
|
+
}[];
|
|
13
|
+
}
|
|
14
|
+
export interface TrainingSummary {
|
|
15
|
+
weeks: number;
|
|
16
|
+
workouts_analyzed: number;
|
|
17
|
+
weekly: WeeklyStats[];
|
|
18
|
+
sets_per_muscle_group: Record<string, number>;
|
|
19
|
+
top_lift_trends: LiftTrend[];
|
|
20
|
+
}
|
|
21
|
+
export declare function computeTrainingSummary(workouts: Workout[], muscleGroupByTemplateId: Map<string, string>, weeks: number, now: Date): TrainingSummary;
|
package/dist/summary.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { estimate1RM } from "./workouts.js";
|
|
2
|
+
import { kgToLb, estLb } from "./units.js";
|
|
3
|
+
/** YYYY-MM-DD of the Monday of d's UTC calendar week. */
|
|
4
|
+
function mondayUtc(d) {
|
|
5
|
+
const daysSinceMonday = (d.getUTCDay() + 6) % 7;
|
|
6
|
+
return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate() - daysSinceMonday))
|
|
7
|
+
.toISOString()
|
|
8
|
+
.slice(0, 10);
|
|
9
|
+
}
|
|
10
|
+
export function computeTrainingSummary(workouts, muscleGroupByTemplateId, weeks, now) {
|
|
11
|
+
const cutoff = now.getTime() - weeks * 7 * 86_400_000;
|
|
12
|
+
const inWindow = workouts.filter((w) => Date.parse(w.start_time) >= cutoff);
|
|
13
|
+
const weekly = new Map();
|
|
14
|
+
const setsPerMuscle = {};
|
|
15
|
+
const perExercise = new Map();
|
|
16
|
+
for (const w of inWindow) {
|
|
17
|
+
const wk = mondayUtc(new Date(w.start_time));
|
|
18
|
+
const stats = weekly.get(wk) ?? { week_start: wk, sessions: 0, volumeKg: 0 };
|
|
19
|
+
weekly.set(wk, stats);
|
|
20
|
+
stats.sessions++;
|
|
21
|
+
for (const e of w.exercises ?? []) {
|
|
22
|
+
const muscle = muscleGroupByTemplateId.get(e.exercise_template_id) ?? "other";
|
|
23
|
+
for (const s of e.sets ?? []) {
|
|
24
|
+
if (s.type === "warmup")
|
|
25
|
+
continue;
|
|
26
|
+
setsPerMuscle[muscle] = (setsPerMuscle[muscle] ?? 0) + 1;
|
|
27
|
+
if (s.weight_kg != null && s.reps != null) {
|
|
28
|
+
const vol = s.weight_kg * s.reps;
|
|
29
|
+
stats.volumeKg += vol;
|
|
30
|
+
const rec = perExercise.get(e.exercise_template_id) ?? { title: e.title, volume: 0, weeklyBest: new Map() };
|
|
31
|
+
perExercise.set(e.exercise_template_id, rec);
|
|
32
|
+
rec.volume += vol;
|
|
33
|
+
const est = estimate1RM(s.weight_kg, s.reps);
|
|
34
|
+
if (est != null && est > (rec.weeklyBest.get(wk) ?? 0))
|
|
35
|
+
rec.weeklyBest.set(wk, est);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
const topLifts = [...perExercise.values()].sort((a, b) => b.volume - a.volume).slice(0, 3);
|
|
41
|
+
return {
|
|
42
|
+
weeks,
|
|
43
|
+
workouts_analyzed: inWindow.length,
|
|
44
|
+
weekly: [...weekly.values()]
|
|
45
|
+
.sort((a, b) => a.week_start.localeCompare(b.week_start))
|
|
46
|
+
.map((s) => ({ week_start: s.week_start, sessions: s.sessions, volume_lb: Math.round(kgToLb(s.volumeKg)) })),
|
|
47
|
+
sets_per_muscle_group: setsPerMuscle,
|
|
48
|
+
top_lift_trends: topLifts.map((t) => ({
|
|
49
|
+
exercise: t.title,
|
|
50
|
+
weekly_best_est_1rm_lb: [...t.weeklyBest.entries()]
|
|
51
|
+
.sort((a, b) => a[0].localeCompare(b[0]))
|
|
52
|
+
.map(([week_start, estKg]) => ({ week_start, est_1rm_lb: estLb(estKg) })),
|
|
53
|
+
})),
|
|
54
|
+
};
|
|
55
|
+
}
|
package/dist/tools.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
+
import { HevyClient } from "./hevy-client.js";
|
|
3
|
+
export declare function createHevyClient(apiKey: string): HevyClient;
|
|
4
|
+
export declare function keyInvalidMessage(status: number, hint: string): string;
|
|
5
|
+
export interface RegisterOptions {
|
|
6
|
+
/** Client-specific guidance appended to the key-invalid error, e.g.
|
|
7
|
+
* "Ask the user to disconnect and reconnect the connector in claude.ai settings."
|
|
8
|
+
* or "Check the HEVY_API_KEY environment variable." */
|
|
9
|
+
keyInvalidHint?: string;
|
|
10
|
+
}
|
|
11
|
+
export declare function registerTools(server: McpServer, client: HevyClient, opts?: RegisterOptions): void;
|
package/dist/tools.js
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { HevyClient, HevyApiError } from "./hevy-client.js";
|
|
3
|
+
import { searchExercises } from "./exercises.js";
|
|
4
|
+
import { buildRoutinePayload } from "./routine-builder.js";
|
|
5
|
+
import { summarizeWorkout, groupExerciseHistory, scanWorkouts } from "./workouts.js";
|
|
6
|
+
import { computeTrainingSummary } from "./summary.js";
|
|
7
|
+
const HISTORY_MAX_PAGES = 15; // × pageSize 10 = 150 most recent workouts
|
|
8
|
+
const SetSchema = z.object({
|
|
9
|
+
type: z.enum(["warmup", "normal", "failure", "dropset"]).optional()
|
|
10
|
+
.describe("Set type; defaults to 'normal'."),
|
|
11
|
+
weight_kg: z.number().nullable().optional()
|
|
12
|
+
.describe("Weight in KILOGRAMS. Omit (or null) for bodyweight/reps_only exercises."),
|
|
13
|
+
weight_lb: z.number().nullable().optional()
|
|
14
|
+
.describe("Weight in pounds — snapped to the nearest 2.5 lb, then converted to kg server-side. Provide weight_kg OR weight_lb, not both."),
|
|
15
|
+
reps: z.number().int().nullable().optional(),
|
|
16
|
+
rpe: z.number().min(6).max(10).nullable().optional()
|
|
17
|
+
.describe("Target RPE. Hevy routines cannot store RPE on sets, so this is folded into the exercise notes automatically."),
|
|
18
|
+
duration_seconds: z.number().int().nullable().optional()
|
|
19
|
+
.describe("Target duration for duration-type exercises (planks, carries). Passed through as-is."),
|
|
20
|
+
distance_meters: z.number().nullable().optional()
|
|
21
|
+
.describe("Target distance for distance-type exercises. Passed through as-is."),
|
|
22
|
+
custom_metric: z.number().nullable().optional(),
|
|
23
|
+
});
|
|
24
|
+
const ExerciseSchema = z.object({
|
|
25
|
+
exercise_template_id: z.string()
|
|
26
|
+
.describe("Template id from search_exercises. NEVER invent ids."),
|
|
27
|
+
superset_id: z.number().int().nullable().optional()
|
|
28
|
+
.describe("Exercises sharing the same integer are supersetted together."),
|
|
29
|
+
rest_seconds: z.number().int().nullable().optional(),
|
|
30
|
+
notes: z.string().optional(),
|
|
31
|
+
sets: z.array(SetSchema).min(1),
|
|
32
|
+
});
|
|
33
|
+
const READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true };
|
|
34
|
+
export function createHevyClient(apiKey) {
|
|
35
|
+
return new HevyClient(apiKey);
|
|
36
|
+
}
|
|
37
|
+
export function keyInvalidMessage(status, hint) {
|
|
38
|
+
return `Your Hevy API key is no longer valid (Hevy returned HTTP ${status}). ${hint} ` +
|
|
39
|
+
"The user can check their key at hevy.com/settings?developer.";
|
|
40
|
+
}
|
|
41
|
+
export function registerTools(server, client, opts = {}) {
|
|
42
|
+
const hint = opts.keyInvalidHint ?? "Update your Hevy API key where you configured this server.";
|
|
43
|
+
let templates = null;
|
|
44
|
+
const library = async () => {
|
|
45
|
+
if (!templates)
|
|
46
|
+
templates = await client.fetchAllExerciseTemplates();
|
|
47
|
+
return templates;
|
|
48
|
+
};
|
|
49
|
+
const ok = (data) => ({ content: [{ type: "text", text: JSON.stringify(data, null, 2) }] });
|
|
50
|
+
const err = (message) => ({ content: [{ type: "text", text: message }], isError: true });
|
|
51
|
+
const run = async (fn) => {
|
|
52
|
+
try {
|
|
53
|
+
return ok(await fn());
|
|
54
|
+
}
|
|
55
|
+
catch (e) {
|
|
56
|
+
if (e instanceof HevyApiError && (e.status === 401 || e.status === 403)) {
|
|
57
|
+
return err(keyInvalidMessage(e.status, hint));
|
|
58
|
+
}
|
|
59
|
+
if (e instanceof Error)
|
|
60
|
+
return err(e.message);
|
|
61
|
+
return err(String(e));
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
server.registerTool("search_exercises", {
|
|
65
|
+
title: "Search exercises",
|
|
66
|
+
description: "Search the user's Hevy exercise library by name (fuzzy). Returns template id, exact title, " +
|
|
67
|
+
"type, muscle group and equipment. type 'weight_reps' takes weight+reps; 'reps_only' takes reps " +
|
|
68
|
+
"and NO weight; type 'duration' takes duration_seconds; distance types take distance_meters. " +
|
|
69
|
+
"Always use this to get exercise_template_id values before create_routine.",
|
|
70
|
+
inputSchema: { query: z.string().describe("Exercise name, e.g. 'bench press' or 'romanian deadlift'") },
|
|
71
|
+
annotations: { title: "Search exercises", ...READ },
|
|
72
|
+
}, async ({ query }) => run(async () => searchExercises(query, await library()).map(({ id, title, type, primary_muscle_group, equipment }) => ({ id, title, type, primary_muscle_group, equipment }))));
|
|
73
|
+
server.registerTool("list_routine_folders", {
|
|
74
|
+
title: "List routine folders",
|
|
75
|
+
description: "List the user's routine folders (id + title). Check this before creating a folder — reuse an existing one when the name matches.",
|
|
76
|
+
inputSchema: {},
|
|
77
|
+
annotations: { title: "List routine folders", ...READ },
|
|
78
|
+
}, async () => run(() => client.listRoutineFolders()));
|
|
79
|
+
server.registerTool("list_routines", {
|
|
80
|
+
title: "List routines",
|
|
81
|
+
description: "List the user's existing routines (id, title, folder_id, exercise_count). Use to avoid creating duplicates. " +
|
|
82
|
+
"Pass query to filter by title.",
|
|
83
|
+
inputSchema: { query: z.string().optional().describe("Optional case-insensitive title substring filter.") },
|
|
84
|
+
annotations: { title: "List routines", ...READ },
|
|
85
|
+
}, async ({ query }) => run(() => client.listRoutines(query)));
|
|
86
|
+
server.registerTool("get_workouts", {
|
|
87
|
+
title: "Get workouts",
|
|
88
|
+
description: "Get the user's most recent logged workouts, newest first, as COMPACT summaries: title, date, " +
|
|
89
|
+
"duration, and per-exercise set count + top set. Use get_workout for full set-by-set detail of one workout.",
|
|
90
|
+
inputSchema: { limit: z.number().int().min(1).max(30).optional().describe("How many workouts to return (default 10, max 30).") },
|
|
91
|
+
annotations: { title: "Get workouts", ...READ },
|
|
92
|
+
}, async ({ limit }) => run(async () => {
|
|
93
|
+
const n = limit ?? 10;
|
|
94
|
+
const { workouts } = await scanWorkouts((p) => client.getWorkoutsPage(p, 10), Math.ceil(n / 10));
|
|
95
|
+
return workouts.slice(0, n).map(summarizeWorkout);
|
|
96
|
+
}));
|
|
97
|
+
server.registerTool("get_workout", {
|
|
98
|
+
title: "Get workout",
|
|
99
|
+
description: "Get one logged workout with every set (weights in kg). Use the id from get_workouts.",
|
|
100
|
+
inputSchema: { workout_id: z.string().describe("Workout id from get_workouts.") },
|
|
101
|
+
annotations: { title: "Get workout", ...READ },
|
|
102
|
+
}, async ({ workout_id }) => run(() => client.getWorkout(workout_id)));
|
|
103
|
+
server.registerTool("get_workout_count", {
|
|
104
|
+
title: "Get workout count",
|
|
105
|
+
description: "Total number of workouts the user has ever logged in Hevy.",
|
|
106
|
+
inputSchema: {},
|
|
107
|
+
annotations: { title: "Get workout count", ...READ },
|
|
108
|
+
}, async () => run(async () => ({ workout_count: await client.getWorkoutCount() })));
|
|
109
|
+
server.registerTool("get_exercise_history", {
|
|
110
|
+
title: "Get exercise history",
|
|
111
|
+
description: "Past performances of ONE exercise across the user's workouts (newest first): per-date sets " +
|
|
112
|
+
"(lb-first, kg preserved) and best estimated 1RM in lb (Epley). Covers the full available history by " +
|
|
113
|
+
"default (a note is added if Hevy truncates the response); pass start_date/end_date (ISO 8601) to narrow the window. Get the " +
|
|
114
|
+
"exercise_template_id from search_exercises or get_workouts.",
|
|
115
|
+
inputSchema: {
|
|
116
|
+
exercise_template_id: z.string().describe("Template id from search_exercises / get_workouts."),
|
|
117
|
+
start_date: z.string().optional().describe("Optional ISO 8601 lower bound, e.g. 2026-06-01T00:00:00Z."),
|
|
118
|
+
end_date: z.string().optional().describe("Optional ISO 8601 upper bound."),
|
|
119
|
+
},
|
|
120
|
+
annotations: { title: "Get exercise history", ...READ },
|
|
121
|
+
}, async ({ exercise_template_id, start_date, end_date }) => run(async () => {
|
|
122
|
+
try {
|
|
123
|
+
const { rows, truncated } = await client.getExerciseHistory(exercise_template_id, start_date, end_date);
|
|
124
|
+
return {
|
|
125
|
+
exercise_template_id,
|
|
126
|
+
entries: groupExerciseHistory(rows),
|
|
127
|
+
...(truncated
|
|
128
|
+
? { note: "Hevy paginated this response; only the first page of history is included — narrow the window with start_date/end_date." }
|
|
129
|
+
: {}),
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
catch (e) {
|
|
133
|
+
if (e instanceof HevyApiError && e.status === 404) {
|
|
134
|
+
return {
|
|
135
|
+
exercise_template_id,
|
|
136
|
+
entries: [],
|
|
137
|
+
note: "No history found — the user may never have performed this exercise, or the id may be wrong (verify via search_exercises).",
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
throw e;
|
|
141
|
+
}
|
|
142
|
+
}));
|
|
143
|
+
server.registerTool("get_routine", {
|
|
144
|
+
title: "Get routine",
|
|
145
|
+
description: "Get one routine in full (all exercises and sets). ALWAYS call this before update_routine so you can " +
|
|
146
|
+
"send back the complete routine.",
|
|
147
|
+
inputSchema: { routine_id: z.union([z.string(), z.number()]).describe("Routine id from list_routines.") },
|
|
148
|
+
annotations: { title: "Get routine", ...READ },
|
|
149
|
+
}, async ({ routine_id }) => run(() => client.getRoutine(routine_id)));
|
|
150
|
+
server.registerTool("get_training_summary", {
|
|
151
|
+
title: "Get training summary",
|
|
152
|
+
description: "Server-computed training overview for the last N weeks: sessions and volume (lb) per week, working " +
|
|
153
|
+
"sets per muscle group, and best-estimated-1RM trend for the top lifts. Much cheaper than fetching " +
|
|
154
|
+
"raw workouts — prefer this for questions like 'how has my training been going?'.",
|
|
155
|
+
inputSchema: { weeks: z.number().int().min(1).max(12).optional().describe("Window in weeks, 1–12 (default 4).") },
|
|
156
|
+
annotations: { title: "Get training summary", ...READ },
|
|
157
|
+
}, async ({ weeks }) => run(async () => {
|
|
158
|
+
const n = weeks ?? 4;
|
|
159
|
+
const cutoff = Date.now() - n * 7 * 86_400_000;
|
|
160
|
+
const { workouts, capped, rateLimited } = await scanWorkouts((p) => client.getWorkoutsPage(p, 10), HISTORY_MAX_PAGES, (w) => Date.parse(w.start_time) < cutoff);
|
|
161
|
+
const byId = new Map((await library()).map((t) => [t.id, t.primary_muscle_group]));
|
|
162
|
+
const summary = computeTrainingSummary(workouts, byId, n, new Date());
|
|
163
|
+
const note = capped
|
|
164
|
+
? "Scan capped at the 150 most recent workouts; earlier weeks in the window may be undercounted."
|
|
165
|
+
: rateLimited
|
|
166
|
+
? `Hevy rate limit hit mid-scan — summary covers only the ${workouts.length} most recent workouts; retry in a minute for full coverage.`
|
|
167
|
+
: undefined;
|
|
168
|
+
return note ? { ...summary, note } : summary;
|
|
169
|
+
}));
|
|
170
|
+
server.registerTool("create_routine_folder", {
|
|
171
|
+
title: "Create routine folder",
|
|
172
|
+
description: "Create a routine folder, or return the existing folder if one with this exact title already exists (never duplicates).",
|
|
173
|
+
inputSchema: { title: z.string() },
|
|
174
|
+
annotations: { title: "Create routine folder", readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
175
|
+
}, async ({ title }) => run(() => client.createRoutineFolder(title)));
|
|
176
|
+
server.registerTool("create_routine", {
|
|
177
|
+
title: "Create routine",
|
|
178
|
+
description: "Create a workout routine in the user's Hevy account. Prescribe weights via weight_lb in 2.5 or " +
|
|
179
|
+
"5 lb increments — the server snaps weight_lb to the nearest 2.5 lb and converts to kg for storage " +
|
|
180
|
+
"(weight_kg is also accepted and stored as-is). RPE targets are folded into exercise notes because " +
|
|
181
|
+
"Hevy routines cannot store per-set RPE. Leave weights null for accessories the user will fill in " +
|
|
182
|
+
"at the gym. Exercises sharing a superset_id integer are supersetted. Ask the user to confirm the " +
|
|
183
|
+
"plan before calling this.",
|
|
184
|
+
inputSchema: {
|
|
185
|
+
title: z.string(),
|
|
186
|
+
folder_id: z.number().int().nullable().optional()
|
|
187
|
+
.describe("Folder id from list_routine_folders / create_routine_folder; null for no folder."),
|
|
188
|
+
notes: z.string().optional(),
|
|
189
|
+
exercises: z.array(ExerciseSchema).min(1),
|
|
190
|
+
},
|
|
191
|
+
annotations: { title: "Create routine", readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
|
192
|
+
}, async (input) => run(async () => {
|
|
193
|
+
const ids = new Set((await library()).map((t) => t.id));
|
|
194
|
+
const payload = buildRoutinePayload(input, ids);
|
|
195
|
+
return client.createRoutine(payload);
|
|
196
|
+
}));
|
|
197
|
+
server.registerTool("update_routine", {
|
|
198
|
+
title: "Update routine (overwrites)",
|
|
199
|
+
description: "Replace an existing routine. WARNING: this OVERWRITES the routine — Hevy replaces its exercises with " +
|
|
200
|
+
"exactly what you send, so first call get_routine and include every exercise you want to keep. " +
|
|
201
|
+
"Folder cannot be changed here. Same input rules as create_routine: prescribe via weight_lb (snapped to 2.5 lb increments; weight_kg passes through as-is), RPE folded into notes, duration/distance/custom-metric targets pass through. " +
|
|
202
|
+
"Ask the user to confirm before calling this.",
|
|
203
|
+
inputSchema: {
|
|
204
|
+
routine_id: z.union([z.string(), z.number()]).describe("Routine id from list_routines / get_routine."),
|
|
205
|
+
title: z.string(),
|
|
206
|
+
notes: z.string().optional(),
|
|
207
|
+
exercises: z.array(ExerciseSchema).min(1),
|
|
208
|
+
},
|
|
209
|
+
annotations: { title: "Update routine (overwrites)", readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
|
|
210
|
+
}, async ({ routine_id, ...input }) => run(async () => {
|
|
211
|
+
const ids = new Set((await library()).map((t) => t.id));
|
|
212
|
+
const { routine } = buildRoutinePayload({ ...input, folder_id: null }, ids);
|
|
213
|
+
const { folder_id: _dropped, ...update } = routine;
|
|
214
|
+
return client.updateRoutine(routine_id, { routine: update });
|
|
215
|
+
}));
|
|
216
|
+
}
|
package/dist/units.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** All unit handling for lb-standard output. Internal math stays in exact kg;
|
|
2
|
+
* rounding happens only at output boundaries, and only in lb space. */
|
|
3
|
+
export declare const KG_PER_LB = 0.45359237;
|
|
4
|
+
export declare const LB_PER_KG: number;
|
|
5
|
+
export declare function kgToLb(kg: number): number;
|
|
6
|
+
/** Nearest plate increment (default 2.5 lb; multiples of 5 are covered). */
|
|
7
|
+
export declare function roundToIncrement(lb: number, inc?: number): number;
|
|
8
|
+
/** Loadable-weight display: stored kg -> lb on a 2.5 lb increment. */
|
|
9
|
+
export declare function displayLb(kg: number | null): number | null;
|
|
10
|
+
/** Estimate display (1RMs): stored kg -> lb at 0.1 precision, no increments. */
|
|
11
|
+
export declare function estLb(kg: number | null): number | null;
|
package/dist/units.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** All unit handling for lb-standard output. Internal math stays in exact kg;
|
|
2
|
+
* rounding happens only at output boundaries, and only in lb space. */
|
|
3
|
+
export const KG_PER_LB = 0.45359237;
|
|
4
|
+
export const LB_PER_KG = 1 / KG_PER_LB;
|
|
5
|
+
export function kgToLb(kg) {
|
|
6
|
+
return kg * LB_PER_KG;
|
|
7
|
+
}
|
|
8
|
+
/** Nearest plate increment (default 2.5 lb; multiples of 5 are covered). */
|
|
9
|
+
export function roundToIncrement(lb, inc = 2.5) {
|
|
10
|
+
return Math.round(lb / inc) * inc;
|
|
11
|
+
}
|
|
12
|
+
/** Loadable-weight display: stored kg -> lb on a 2.5 lb increment. */
|
|
13
|
+
export function displayLb(kg) {
|
|
14
|
+
return kg == null ? null : roundToIncrement(kgToLb(kg));
|
|
15
|
+
}
|
|
16
|
+
/** Estimate display (1RMs): stored kg -> lb at 0.1 precision, no increments. */
|
|
17
|
+
export function estLb(kg) {
|
|
18
|
+
return kg == null ? null : Math.round(kgToLb(kg) * 10) / 10;
|
|
19
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { type Workout, type WorkoutSet, type WorkoutsPage, type ExerciseHistoryRow } from "./hevy-client.js";
|
|
2
|
+
export interface ExerciseSummary {
|
|
3
|
+
title: string;
|
|
4
|
+
exercise_template_id: string;
|
|
5
|
+
set_count: number;
|
|
6
|
+
top_set: string | null;
|
|
7
|
+
}
|
|
8
|
+
export interface WorkoutSummary {
|
|
9
|
+
id: string;
|
|
10
|
+
title: string;
|
|
11
|
+
date: string;
|
|
12
|
+
duration_minutes: number | null;
|
|
13
|
+
exercises: ExerciseSummary[];
|
|
14
|
+
}
|
|
15
|
+
export interface HistoryEntry {
|
|
16
|
+
date: string;
|
|
17
|
+
workout_title: string;
|
|
18
|
+
sets: {
|
|
19
|
+
type: string;
|
|
20
|
+
weight_kg: number | null;
|
|
21
|
+
weight_lb: number | null;
|
|
22
|
+
reps: number | null;
|
|
23
|
+
duration_seconds: number | null;
|
|
24
|
+
distance_meters: number | null;
|
|
25
|
+
rpe: number | null;
|
|
26
|
+
}[];
|
|
27
|
+
best_est_1rm_lb: number | null;
|
|
28
|
+
}
|
|
29
|
+
/** Epley estimated 1RM, rounded to 1 decimal. Null unless weight and positive reps are present. */
|
|
30
|
+
export declare function estimate1RM(weightKg: number | null, reps: number | null): number | null;
|
|
31
|
+
export declare function formatSet(s: WorkoutSet): string | null;
|
|
32
|
+
export declare function topSet(sets: WorkoutSet[]): WorkoutSet | null;
|
|
33
|
+
export declare function summarizeWorkout(w: Workout): WorkoutSummary;
|
|
34
|
+
/** Group the native endpoint's flat set rows into per-workout entries, newest
|
|
35
|
+
* first. Row order within a workout is preserved (API order = set order). */
|
|
36
|
+
export declare function groupExerciseHistory(rows: ExerciseHistoryRow[]): HistoryEntry[];
|
|
37
|
+
/**
|
|
38
|
+
* Walk /v1/workouts pages (newest first) via fetchPage until the last page,
|
|
39
|
+
* maxPages, or the first workout matching isPastCutoff. capped=true only when
|
|
40
|
+
* maxPages truncated a longer history. A mid-scan 429 returns what was already
|
|
41
|
+
* fetched with rateLimited=true; a first-page 429 (nothing useful yet) and all
|
|
42
|
+
* other errors still throw.
|
|
43
|
+
*/
|
|
44
|
+
export declare function scanWorkouts(fetchPage: (page: number) => Promise<WorkoutsPage>, maxPages: number, isPastCutoff?: (w: Workout) => boolean): Promise<{
|
|
45
|
+
workouts: Workout[];
|
|
46
|
+
capped: boolean;
|
|
47
|
+
rateLimited: boolean;
|
|
48
|
+
}>;
|
package/dist/workouts.js
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { HevyApiError } from "./hevy-client.js";
|
|
2
|
+
import { displayLb, estLb } from "./units.js";
|
|
3
|
+
/** Epley estimated 1RM, rounded to 1 decimal. Null unless weight and positive reps are present. */
|
|
4
|
+
export function estimate1RM(weightKg, reps) {
|
|
5
|
+
if (weightKg == null || reps == null || reps <= 0)
|
|
6
|
+
return null;
|
|
7
|
+
if (reps === 1)
|
|
8
|
+
return weightKg;
|
|
9
|
+
return Math.round(weightKg * (1 + reps / 30) * 10) / 10;
|
|
10
|
+
}
|
|
11
|
+
export function formatSet(s) {
|
|
12
|
+
const parts = [];
|
|
13
|
+
if (s.weight_kg != null)
|
|
14
|
+
parts.push(`${displayLb(s.weight_kg)} lb`);
|
|
15
|
+
if (s.reps != null)
|
|
16
|
+
parts.push(s.weight_kg != null ? `× ${s.reps}` : `${s.reps} reps`);
|
|
17
|
+
if (s.distance_meters != null)
|
|
18
|
+
parts.push(`${s.distance_meters} m`);
|
|
19
|
+
if (s.duration_seconds != null)
|
|
20
|
+
parts.push(`${s.duration_seconds} s`);
|
|
21
|
+
return parts.length ? parts.join(" ") : null;
|
|
22
|
+
}
|
|
23
|
+
function setScore(s) {
|
|
24
|
+
const est = estimate1RM(s.weight_kg, s.reps);
|
|
25
|
+
if (est != null)
|
|
26
|
+
return est;
|
|
27
|
+
if (s.weight_kg != null)
|
|
28
|
+
return s.weight_kg;
|
|
29
|
+
if (s.reps != null)
|
|
30
|
+
return s.reps;
|
|
31
|
+
if (s.duration_seconds != null)
|
|
32
|
+
return s.duration_seconds;
|
|
33
|
+
if (s.distance_meters != null)
|
|
34
|
+
return s.distance_meters;
|
|
35
|
+
return -1;
|
|
36
|
+
}
|
|
37
|
+
export function topSet(sets) {
|
|
38
|
+
const working = sets.filter((s) => s.type !== "warmup");
|
|
39
|
+
const pool = working.length ? working : sets;
|
|
40
|
+
if (!pool.length)
|
|
41
|
+
return null;
|
|
42
|
+
return pool.reduce((best, s) => (setScore(s) > setScore(best) ? s : best));
|
|
43
|
+
}
|
|
44
|
+
function durationMinutes(start, end) {
|
|
45
|
+
const ms = Date.parse(end) - Date.parse(start);
|
|
46
|
+
return Number.isFinite(ms) && ms > 0 ? Math.round(ms / 60_000) : null;
|
|
47
|
+
}
|
|
48
|
+
export function summarizeWorkout(w) {
|
|
49
|
+
return {
|
|
50
|
+
id: w.id,
|
|
51
|
+
title: w.title,
|
|
52
|
+
date: w.start_time,
|
|
53
|
+
duration_minutes: durationMinutes(w.start_time, w.end_time),
|
|
54
|
+
exercises: (w.exercises ?? []).map((e) => {
|
|
55
|
+
const top = topSet(e.sets ?? []);
|
|
56
|
+
return {
|
|
57
|
+
title: e.title,
|
|
58
|
+
exercise_template_id: e.exercise_template_id,
|
|
59
|
+
set_count: (e.sets ?? []).length,
|
|
60
|
+
top_set: top ? formatSet(top) : null,
|
|
61
|
+
};
|
|
62
|
+
}),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
/** Group the native endpoint's flat set rows into per-workout entries, newest
|
|
66
|
+
* first. Row order within a workout is preserved (API order = set order). */
|
|
67
|
+
export function groupExerciseHistory(rows) {
|
|
68
|
+
const byWorkout = new Map();
|
|
69
|
+
for (const r of rows) {
|
|
70
|
+
let g = byWorkout.get(r.workout_id);
|
|
71
|
+
if (!g) {
|
|
72
|
+
g = {
|
|
73
|
+
entry: { date: r.workout_start_time, workout_title: r.workout_title, sets: [], best_est_1rm_lb: null },
|
|
74
|
+
bestKg: null,
|
|
75
|
+
};
|
|
76
|
+
byWorkout.set(r.workout_id, g);
|
|
77
|
+
}
|
|
78
|
+
g.entry.sets.push({
|
|
79
|
+
type: r.set_type,
|
|
80
|
+
weight_kg: r.weight_kg,
|
|
81
|
+
weight_lb: displayLb(r.weight_kg),
|
|
82
|
+
reps: r.reps,
|
|
83
|
+
duration_seconds: r.duration_seconds,
|
|
84
|
+
distance_meters: r.distance_meters,
|
|
85
|
+
rpe: r.rpe,
|
|
86
|
+
});
|
|
87
|
+
const est = estimate1RM(r.weight_kg, r.reps);
|
|
88
|
+
if (est != null && (g.bestKg == null || est > g.bestKg))
|
|
89
|
+
g.bestKg = est;
|
|
90
|
+
}
|
|
91
|
+
return [...byWorkout.values()]
|
|
92
|
+
.map((g) => ({ ...g.entry, best_est_1rm_lb: estLb(g.bestKg) }))
|
|
93
|
+
.sort((a, b) => b.date.localeCompare(a.date));
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Walk /v1/workouts pages (newest first) via fetchPage until the last page,
|
|
97
|
+
* maxPages, or the first workout matching isPastCutoff. capped=true only when
|
|
98
|
+
* maxPages truncated a longer history. A mid-scan 429 returns what was already
|
|
99
|
+
* fetched with rateLimited=true; a first-page 429 (nothing useful yet) and all
|
|
100
|
+
* other errors still throw.
|
|
101
|
+
*/
|
|
102
|
+
export async function scanWorkouts(fetchPage, maxPages, isPastCutoff) {
|
|
103
|
+
const collected = [];
|
|
104
|
+
for (let page = 1; page <= maxPages; page++) {
|
|
105
|
+
let data;
|
|
106
|
+
try {
|
|
107
|
+
data = await fetchPage(page);
|
|
108
|
+
}
|
|
109
|
+
catch (e) {
|
|
110
|
+
if (e instanceof HevyApiError && e.status === 429 && collected.length) {
|
|
111
|
+
return { workouts: collected, capped: false, rateLimited: true };
|
|
112
|
+
}
|
|
113
|
+
throw e;
|
|
114
|
+
}
|
|
115
|
+
for (const w of data.workouts) {
|
|
116
|
+
if (isPastCutoff?.(w))
|
|
117
|
+
return { workouts: collected, capped: false, rateLimited: false };
|
|
118
|
+
collected.push(w);
|
|
119
|
+
}
|
|
120
|
+
if (page >= data.page_count)
|
|
121
|
+
return { workouts: collected, capped: false, rateLimited: false };
|
|
122
|
+
}
|
|
123
|
+
return { workouts: collected, capped: true, rateLimited: false };
|
|
124
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@almostjacked/hevy-mcp-core",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Core for hevy-mcp: Hevy API client and MCP tool registrations (unofficial).",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": "./dist/index.js"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"dist"
|
|
13
|
+
],
|
|
14
|
+
"dependencies": {
|
|
15
|
+
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
16
|
+
"zod": "^4.4.3"
|
|
17
|
+
},
|
|
18
|
+
"devDependencies": {
|
|
19
|
+
"@types/node": "^22.0.0",
|
|
20
|
+
"typescript": "^5.5.0",
|
|
21
|
+
"vitest": "^2.0.0"
|
|
22
|
+
},
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=18"
|
|
25
|
+
},
|
|
26
|
+
"license": "MIT",
|
|
27
|
+
"author": "AJ Wallace <ajwallacemusic@gmail.com>",
|
|
28
|
+
"repository": {
|
|
29
|
+
"type": "git",
|
|
30
|
+
"url": "git+https://github.com/almostjacked/hevy-mcp.git",
|
|
31
|
+
"directory": "packages/core"
|
|
32
|
+
},
|
|
33
|
+
"mcpName": "io.github.almostjacked/hevy-mcp",
|
|
34
|
+
"scripts": {
|
|
35
|
+
"build": "tsc -p tsconfig.json",
|
|
36
|
+
"test": "vitest run",
|
|
37
|
+
"typecheck": "tsc --noEmit -p tsconfig.json"
|
|
38
|
+
}
|
|
39
|
+
}
|