From 77b4d14ac63eb87cf2338a77f129acff71eb09c0 Mon Sep 17 00:00:00 2001 From: daniel-bernardino747 Date: Thu, 12 Nov 2026 10:54:24 -0300 Subject: [PATCH] MCP: read, create, change and delete programs and their workout days (#154) An MCP client could list programs and start the day's workout, but not build or adjust a routine. Seven tools close that: - get_program (mcp:read): one program with its days and each exercise's sets, reps, weight, rest and notes. - create_program, update_program, create_template, update_template (mcp:write). - delete_program, delete_template (mcp:destroy, confirm: true). The writes follow the app's own routes: only the account that made a program changes it (program-access.js), fields merge by the newer-wins rule, and a day's exercises go through the same per-uuid merge and tombstones as PUT /api/templates/:id. update_template takes the day's whole list: an exercise sent with its uuid is changed in place and keeps what the tools don't expose (supersets, per-week targets), one without a uuid is added, one left out is removed. Tests: scripts/mcp-programs.test.js. --- CHANGELOG.md | 4 + README.md | 2 +- scripts/mcp-programs.test.js | 309 ++++++++++++++++++++++++ server/lib/mcp/_program-write.js | 221 +++++++++++++++++ server/lib/mcp/tools/create-program.js | 55 +++++ server/lib/mcp/tools/create-template.js | 56 +++++ server/lib/mcp/tools/delete-program.js | 74 ++++++ server/lib/mcp/tools/get-program.js | 53 ++++ server/lib/mcp/tools/index.js | 13 + server/lib/mcp/tools/update-program.js | 67 +++++ server/lib/mcp/tools/update-template.js | 65 +++++ 11 files changed, 918 insertions(+), 1 deletion(-) create mode 100644 scripts/mcp-programs.test.js create mode 100644 server/lib/mcp/_program-write.js create mode 100644 server/lib/mcp/tools/create-program.js create mode 100644 server/lib/mcp/tools/create-template.js create mode 100644 server/lib/mcp/tools/delete-program.js create mode 100644 server/lib/mcp/tools/get-program.js create mode 100644 server/lib/mcp/tools/update-program.js create mode 100644 server/lib/mcp/tools/update-template.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 50137ef9..7706f927 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [Unreleased] +### Added + +- **Create and change programs through MCP** ([#154](https://github.com/TraceApps/lifttrace/issues/154)). `get_program` reads one program with its workout days and each exercise's sets, reps, weight and rest. With `mcp:write`, `create_program`, `update_program`, `create_template` and `update_template` build a program and change its days: an exercise sent back with its `uuid` is changed in place, one without is added, one left out is removed. With `mcp:destroy`, `delete_program` and `delete_template` remove them after `confirm: true`. Only programs you made can be changed, not a coach's or a starter program, and they sync to your devices like an edit made in the app. [MCP](https://traceapps.github.io/docs/lifttrace/mcp/) + ### Security - **Tokens, keys and passwords saved in Settings are stored encrypted, and the ones only the server uses never reach the app** (from [cooktrace#92](https://github.com/TraceApps/cooktrace/issues/92), thanks @stupleb). The NutriTrace link token, the ntfy and Gotify tokens and the music server's sign-in stay on the server: Settings shows a saved one as dots, saving the dots keeps it, and typing a new one replaces it. The AI key, ExerciseDB key and music server password still go to your own signed-in app, which uses them itself. All of them are stored encrypted with `TOKEN_ENC_KEY`, so the database, a backup or an export never holds them in plain text; ones saved before are encrypted when the server starts. Changing `TOKEN_ENC_KEY`, or `JWT_SECRET` when it isn't set, means entering them again. diff --git a/README.md b/README.md index dc5e38a5..4a36fc0e 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,7 @@ LiftTrace runs entirely in a single Docker container on your own hardware, with - **Workout history import.** Bring your old log in from Strong, Hevy, FitNotes, Jefit (CSV) or Garmin FIT files. → [full guide](https://traceapps.github.io/docs/lifttrace/import/) - **Multi-user and OIDC SSO.** Role-based access (admin/trainer/member), invites, session policy, [two-step sign-in](https://traceapps.github.io/docs/auth/two-step/) with an authenticator app, plus OIDC 1.0 SSO via Authentik, Keycloak, Pocket ID, Authelia, Google, Auth0, or any compliant provider. → [full guide](https://traceapps.github.io/docs/auth/oidc/) - **Works without a connection.** In a gym with no signal the web app still opens, today's workout is there, and you keep logging: sets, body stats, cardio, your own exercises and settings. Changes go up on their own when the connection returns, merged set by set. → [full guide](https://traceapps.github.io/docs/lifttrace/features/#offline) -- **MCP and REST API.** AI clients and scripts read your workouts, records, progress and body stats over a date range, and can start your program's workout for the day and log sets and body stats. Off by default. → [full guide](https://traceapps.github.io/docs/lifttrace/mcp/) +- **MCP and REST API.** AI clients and scripts read your workouts, records, progress and body stats over a date range, and can start your program's workout for the day, log sets and body stats, and create and change your programs. Off by default. → [full guide](https://traceapps.github.io/docs/lifttrace/mcp/) - **Native Android app.** Local-only mode with on-device SQLite, or connect to your self-hosted server for sync, over HTTPS or [plain HTTP on your own network](https://traceapps.github.io/docs/getting-started/lan-http/). Media3 ExoPlayer, WorkManager reminders, biometric sign-in. → [full guide](https://traceapps.github.io/docs/mobile/install/) - **Wear OS.** A watch app for Wear OS 3 and up: the set you are on with weight and reps already filled in, what you lifted last time, the session timer, started, paused and stopped from either device, any set in the session open to change, sets added or put back to not done, supersets alternating properly, holds counted down and logged, and the rest timer buzzing on your wrist even with the watch face back, plus a tile and a watch face complication. Finish the workout without touching the phone. It talks to your server itself, so it keeps logging in a basement gym with the phone in a locker, and it pairs itself when you sign in on the phone. → [full guide](https://traceapps.github.io/docs/lifttrace/wear/) - **Foldables (preliminary).** Half open like a book, Settings puts its section list on one side of the crease and the section on the other, and dialogs, sheets, the rest timer and Trace keep off the fold. Opened flat or on a tablet, Programs and Exercises split into a list and a preview pane, and the Diary keeps its session column beside the exercises. diff --git a/scripts/mcp-programs.test.js b/scripts/mcp-programs.test.js new file mode 100644 index 00000000..32ee2730 --- /dev/null +++ b/scripts/mcp-programs.test.js @@ -0,0 +1,309 @@ +/** + * Integration checks for the MCP tools that read and change programs and + * their workout days (issue #154): get_program, create_program, + * update_program, create_template, update_template, delete_program and + * delete_template. Uses a temporary SQLite database and calls the registered + * handlers directly, as scripts/mcp-range-integration.test.js does. + */ +import assert from 'node:assert/strict'; +import test, { after, before } from 'node:test'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +const TMP_DB = path.join(os.tmpdir(), `mcp-programs-lt-${process.pid}-${Date.now()}.db`); +process.env.DB_PATH = TMP_DB; +process.env.NODE_ENV = 'test'; + +let db, tools; +try { + ({ default: db } = await import('../server/db.js')); + tools = await import('../server/lib/mcp/tools/index.js'); +} catch (e) { + test('MCP program tools skipped (native module unavailable)', { skip: true }, () => {}); + console.warn(`[mcp-programs] skipping: ${(e?.message || e).split('\n')[0]}`); + process.exit(0); +} + +class MockServer { + constructor() { this.tools = new Map(); } + registerTool(name, definition, handler) { this.tools.set(name, { definition, handler }); } + async call(name, args = {}) { + const tool = this.tools.get(name); + if (!tool) throw new Error(`tool ${name} not registered`); + return tool.handler(args); + } +} + +function serverFor(userId) { + const s = new MockServer(); + tools.registerReadTools(s, { userId }); + tools.registerWriteTools(s, { userId }); + tools.registerDestroyTools(s, { userId }); + return s; +} + +const ok = (result) => { + assert.notEqual(result.isError, true, result.content?.[0]?.text); + return result.structuredContent; +}; +const refused = (result) => { + assert.equal(result.isError, true, 'expected the tool to refuse'); + return result.content[0].text; +}; + +let me, other, mine, theirs, press, row, privateLift; + +before(() => { + const user = (name) => db.prepare( + "INSERT INTO users (username, password_hash, role) VALUES (?, 'x', 'member')" + ).run(name).lastInsertRowid; + me = user('mcp-programs-me'); + other = user('mcp-programs-other'); + mine = serverFor(me); + theirs = serverFor(other); + const exercise = (name, owner) => db.prepare( + 'INSERT INTO exercises (name, is_global, created_by) VALUES (?, ?, ?)' + ).run(name, owner == null ? 1 : 0, owner).lastInsertRowid; + press = exercise('Programs Test Press', null); + row = exercise('Programs Test Row', null); + privateLift = exercise('Programs Test Private Lift', other); +}); + +after(() => { + try { db.close(); } catch { /* already closed */ } + for (const f of [TMP_DB, `${TMP_DB}-wal`, `${TMP_DB}-shm`]) fs.rmSync(f, { force: true }); +}); + +test('the read, write and destroy tools register behind their own gates', () => { + const names = (register) => { const s = new MockServer(); register(s, { userId: me }); return [...s.tools.keys()]; }; + const read = names(tools.registerReadTools); + const write = names(tools.registerWriteTools); + const destroy = names(tools.registerDestroyTools); + assert.ok(read.includes('get_program')); + for (const t of ['create_program', 'update_program', 'create_template', 'update_template']) { + assert.ok(write.includes(t), `${t} is a write tool`); + assert.ok(!read.includes(t), `${t} must not register on a read-only token`); + } + for (const t of ['delete_program', 'delete_template']) { + assert.ok(destroy.includes(t), `${t} is a destroy tool`); + assert.ok(!read.includes(t) && !write.includes(t), `${t} must need the destroy gate`); + } +}); + +test('create_program makes an empty private program the caller owns', async () => { + const { program } = ok(await mine.call('create_program', { name: ' Push Pull Legs ', goal: 'strength' })); + assert.equal(program.name, 'Push Pull Legs'); + assert.equal(program.goal, 'strength'); + assert.equal(program.duration_weeks, 1); + assert.equal(program.advance_mode, 'sessions'); + assert.equal(program.on_complete, 'hold'); + + const stored = db.prepare('SELECT * FROM programs WHERE id = ?').get(program.program_id); + assert.equal(stored.created_by, me); + assert.equal(stored.visibility, 'private'); + + const read = ok(await mine.call('get_program', { program_id: program.program_id })); + assert.equal(read.can_edit, true); + assert.equal(read.is_active, false); + assert.deepEqual(read.templates, []); + + const listed = ok(await mine.call('list_programs')); + assert.ok(listed.programs.some(p => p.program_id === program.program_id)); +}); + +test('create_template stores exercises the way the app\'s editor does', async () => { + const { program } = ok(await mine.call('create_program', { name: 'Template shapes' })); + const { template } = ok(await mine.call('create_template', { + program_id: program.program_id, + name: 'Push', + day_label: 'Monday', + exercises: [ + { exercise_id: press, sets: 4, reps: '6-8', weight: 80, rest_sec: 120, notes: 'Pause on the chest' }, + { exercise_name: 'programs test ROW' }, + { exercise_name: 'Sled drag in the car park', sets: 2, reps: 1 }, + ], + })); + assert.equal(template.name, 'Push'); + assert.equal(template.day_label, 'Monday'); + assert.equal(template.exercises.length, 3); + + const [a, b, c] = template.exercises; + assert.deepEqual( + { id: a.exercise_id, name: a.exercise_name, sets: a.sets, reps: a.reps, weight: a.weight, rest: a.rest_sec, notes: a.notes }, + { id: press, name: 'Programs Test Press', sets: 4, reps: '6-8', weight: '80', rest: 120, notes: 'Pause on the chest' } + ); + // A name that is a library exercise's: that exercise, so its history follows. + assert.equal(b.exercise_id, row); + assert.equal(b.exercise_name, 'Programs Test Row'); + assert.equal(b.sets, 3, 'three sets by default, as the editor adds an exercise'); + // A name that isn't: a free-text exercise. + assert.equal(c.exercise_id, null); + assert.equal(c.exercise_name, 'Sled drag in the car park'); + assert.equal(c.reps, '1'); + for (const e of template.exercises) assert.match(e.uuid, /^[0-9a-f-]{36}$/); + + const stored = JSON.parse(db.prepare('SELECT exercises FROM workout_templates WHERE id = ?').get(template.template_id).exercises); + assert.deepEqual( + { sets: stored[0].target_sets, reps: stored[0].target_reps, weight: stored[0].target_weight, list: stored[0].sets }, + { sets: 4, reps: '6-8', weight: '80', list: [] } + ); + + // A second day goes after the first. + const second = ok(await mine.call('create_template', { program_id: program.program_id, name: 'Pull' })); + const read = ok(await mine.call('get_program', { program_id: program.program_id })); + assert.deepEqual(read.templates.map(t => t.name), ['Push', 'Pull']); + assert.deepEqual(second.template.exercises, []); +}); + +test('update_template changes, adds and removes exercises, and keeps what it wasn\'t sent', async () => { + const { program } = ok(await mine.call('create_program', { name: 'Template edits' })); + const { template } = ok(await mine.call('create_template', { + program_id: program.program_id, + name: 'Day A', + exercises: [ + { exercise_id: press, sets: 3, reps: 10, weight: 60, notes: 'Keep me' }, + { exercise_id: row, sets: 3, reps: 12 }, + ], + })); + const [pressEx, rowEx] = template.exercises; + + // What the app's editor adds and these tools don't expose: it must survive an edit. + const stored = JSON.parse(db.prepare('SELECT exercises FROM workout_templates WHERE id = ?').get(template.template_id).exercises); + stored[0].weeks = [null, { sets: 5, reps: '5' }]; + stored[0].superset_id = 7; + db.prepare('UPDATE workout_templates SET exercises = ? WHERE id = ?').run(JSON.stringify(stored), template.template_id); + + const updated = ok(await mine.call('update_template', { + template_id: template.template_id, + name: 'Day A (heavy)', + exercises: [ + { exercise_name: 'Farmer walk', sets: 2 }, + { uuid: pressEx.uuid, sets: 5, weight: '82.5' }, + ], + })).template; + + assert.equal(updated.name, 'Day A (heavy)'); + assert.deepEqual(updated.exercises.map(e => e.exercise_name), ['Farmer walk', 'Programs Test Press'], 'the order sent, the row left out removed'); + const kept = updated.exercises[1]; + assert.equal(kept.uuid, pressEx.uuid); + assert.deepEqual( + { sets: kept.sets, reps: kept.reps, weight: kept.weight, notes: kept.notes, superset: kept.superset_id, weekly: kept.has_weekly_plan }, + { sets: 5, reps: '10', weight: '82.5', notes: 'Keep me', superset: 7, weekly: true } + ); + + // The removed exercise has a tombstone, so a device that still has it doesn't bring it back. + const tombstones = db.prepare( + "SELECT uuid FROM workout_tombstones WHERE date = ? AND kind = 'template_exercise'" + ).all(`template:${template.template_id}`).map(r => r.uuid); + assert.deepEqual(tombstones, [rowEx.uuid]); + + // Name alone: the exercises are left as they are. + const renamed = ok(await mine.call('update_template', { template_id: template.template_id, day_label: 'Friday' })).template; + assert.equal(renamed.day_label, 'Friday'); + assert.equal(renamed.name, 'Day A (heavy)'); + assert.equal(renamed.exercises.length, 2); + + // An empty list clears the day. + const cleared = ok(await mine.call('update_template', { template_id: template.template_id, exercises: [] })).template; + assert.deepEqual(cleared.exercises, []); +}); + +test('update_template replaces a day whose exercises have no uuid yet', async () => { + const { program } = ok(await mine.call('create_program', { name: 'Old shape' })); + const { template } = ok(await mine.call('create_template', { program_id: program.program_id, name: 'Legacy' })); + db.prepare('UPDATE workout_templates SET exercises = ? WHERE id = ?').run(JSON.stringify([ + { exercise_name: 'Old One', target_sets: 3, target_reps: '10', sets: [] }, + { exercise_name: 'Old Two', target_sets: 3, target_reps: '10', sets: [] }, + ]), template.template_id); + + const read = ok(await mine.call('get_program', { program_id: program.program_id })); + assert.deepEqual(read.templates[0].exercises.map(e => e.uuid), [null, null]); + + const updated = ok(await mine.call('update_template', { + template_id: template.template_id, + exercises: [{ exercise_id: press }], + })).template; + assert.deepEqual(updated.exercises.map(e => e.exercise_name), ['Programs Test Press']); +}); + +test('update_program changes only the fields sent', async () => { + const { program } = ok(await mine.call('create_program', { name: 'Before', description: 'Kept', goal: 'cutting' })); + const updated = ok(await mine.call('update_program', { + program_id: program.program_id, name: 'After', duration_weeks: 8, advance_mode: 'calendar', on_complete: 'repeat', + })).program; + assert.deepEqual(updated, { + program_id: program.program_id, name: 'After', description: 'Kept', goal: 'cutting', + duration_weeks: 8, advance_mode: 'calendar', on_complete: 'repeat', + }); + assert.match(refused(await mine.call('update_program', { program_id: program.program_id })), /Nothing to change/); +}); + +test('bad input is refused with a message that says what to do', async () => { + const { program } = ok(await mine.call('create_program', { name: 'Refusals' })); + const { template } = ok(await mine.call('create_template', { program_id: program.program_id, name: 'Day' })); + + assert.match(refused(await mine.call('create_template', { + program_id: program.program_id, name: 'Bad', exercises: [{ exercise_id: 987654 }], + })), /Exercise 987654 not found/); + // Another account's private exercise is not there to use. + assert.match(refused(await mine.call('create_template', { + program_id: program.program_id, name: 'Bad', exercises: [{ exercise_id: privateLift }], + })), /not found/); + assert.match(refused(await mine.call('create_template', { + program_id: program.program_id, name: 'Bad', exercises: [{ sets: 3 }], + })), /exercise_id or an exercise_name/); + assert.match(refused(await mine.call('update_template', { + template_id: template.template_id, exercises: [{ uuid: 'not-a-real-uuid', sets: 3 }], + })), /No exercise with uuid/); + assert.match(refused(await mine.call('update_template', { template_id: template.template_id })), /Nothing to change/); + + // A refused create leaves nothing behind. + const read = ok(await mine.call('get_program', { program_id: program.program_id })); + assert.deepEqual(read.templates.map(t => t.name), ['Day']); +}); + +test('another account\'s program is not found, and a starter program is read-only', async () => { + const { program } = ok(await mine.call('create_program', { name: 'Mine only' })); + const { template } = ok(await mine.call('create_template', { program_id: program.program_id, name: 'Day' })); + + assert.match(refused(await theirs.call('get_program', { program_id: program.program_id })), /not found/); + assert.match(refused(await theirs.call('update_program', { program_id: program.program_id, name: 'Taken' })), /not found/); + assert.match(refused(await theirs.call('create_template', { program_id: program.program_id, name: 'Sneaky' })), /not found/); + assert.match(refused(await theirs.call('update_template', { template_id: template.template_id, name: 'Sneaky' })), /not found/); + assert.match(refused(await theirs.call('delete_template', { template_id: template.template_id, confirm: true })), /not found/); + assert.match(refused(await theirs.call('delete_program', { program_id: program.program_id, confirm: true })), /not found/); + assert.equal(db.prepare('SELECT name FROM programs WHERE id = ?').get(program.program_id).name, 'Mine only'); + + // A starter program: no maker, shared. Everyone reads it, nobody changes it. + const starter = db.prepare( + "INSERT INTO programs (name, created_by, visibility) VALUES ('Starter Plan', NULL, 'shared')" + ).run().lastInsertRowid; + const day = db.prepare( + "INSERT INTO workout_templates (program_id, name, order_index, exercises) VALUES (?, 'Starter Day', 0, '[]')" + ).run(starter).lastInsertRowid; + const read = ok(await mine.call('get_program', { program_id: starter })); + assert.equal(read.can_edit, false); + assert.match(refused(await mine.call('update_program', { program_id: starter, name: 'Mine now' })), /can't be changed/); + assert.match(refused(await mine.call('update_template', { template_id: day, name: 'Mine now' })), /can't be changed/); + assert.match(refused(await mine.call('delete_program', { program_id: starter, confirm: true })), /can't be changed/); +}); + +test('delete_template and delete_program need confirm: true and then remove it', async () => { + const { program } = ok(await mine.call('create_program', { name: 'To delete' })); + const a = ok(await mine.call('create_template', { program_id: program.program_id, name: 'A' })).template; + ok(await mine.call('create_template', { program_id: program.program_id, name: 'B' })); + + assert.match(refused(await mine.call('delete_template', { template_id: a.template_id, confirm: false })), /confirm: true/); + assert.match(refused(await mine.call('delete_program', { program_id: program.program_id, confirm: false })), /confirm: true/); + assert.equal(ok(await mine.call('get_program', { program_id: program.program_id })).templates.length, 2); + + const gone = ok(await mine.call('delete_template', { template_id: a.template_id, confirm: true })); + assert.deepEqual({ deleted: gone.deleted, name: gone.name }, { deleted: true, name: 'A' }); + assert.deepEqual(ok(await mine.call('get_program', { program_id: program.program_id })).templates.map(t => t.name), ['B']); + assert.match(refused(await mine.call('delete_template', { template_id: a.template_id, confirm: true })), /not found/); + + ok(await mine.call('delete_program', { program_id: program.program_id, confirm: true })); + assert.match(refused(await mine.call('get_program', { program_id: program.program_id })), /not found/); + assert.ok(!ok(await mine.call('list_programs')).programs.some(p => p.program_id === program.program_id)); +}); diff --git a/server/lib/mcp/_program-write.js b/server/lib/mcp/_program-write.js new file mode 100644 index 00000000..2698e626 --- /dev/null +++ b/server/lib/mcp/_program-write.js @@ -0,0 +1,221 @@ +/** + * Shared pieces for the MCP tools that read and change programs and their + * workout days (issue #154): get_program, create_program, update_program, + * create_template, update_template, delete_program, delete_template. + * + * The writes mirror server/routes/programs.js and server/routes/templates.js: + * the same access rule (lib/program-access.js: only the account that made a + * program changes it), the same field-by-field merge (lib/newer-wins.js) and + * the same per-exercise merge and tombstones for a day's exercises + * (lib/workout-merge.js). A tool call is an edit made now, so the helpers + * that read a request's edit time get no request. + * + * A day's exercises are stored as the app's editor writes them + * (target_sets, target_reps, target_weight, ...). The tools take and return + * a shorter form (sets, reps, weight) and convert here, so a caller never + * has to know the stored one. Whatever a stored exercise holds that the + * short form doesn't (a superset, per-set targets, a multi-week plan) is + * kept as it is when the exercise is sent back with its uuid. + */ +import { z } from 'zod'; +import db from '../../db.js'; +import { foldText } from '../search-text.js'; +import { mergeExercises, ensureExerciseUuids } from '../workout-merge.js'; +import { applyToBody, stampMerged } from '../newer-wins.js'; +import { syncOf } from '../sync-fields.js'; +import { programFor } from '../program-access.js'; + +export const MAX_NAME_LENGTH = 100; +export const MAX_DESCRIPTION_LENGTH = 1000; +export const MAX_NOTES_LENGTH = 500; +export const MAX_TARGET_LENGTH = 20; +export const MAX_TEMPLATE_EXERCISES = 40; +export const MAX_TARGET_SETS = 20; +export const MAX_REST_SEC = 3600; +export const MAX_PROGRAM_WEEKS = 52; +// The goals the app's program form offers (src/lib/workout.js GOALS). +export const PROGRAM_GOALS = ['general', 'strength', 'endurance', 'cutting', 'bulking', 'maintenance']; + +const target = z.union([z.string().max(MAX_TARGET_LENGTH), z.number().nonnegative()]); + +/** One exercise of a workout day, as the tools take it. */ +export const EXERCISE_INPUT = z.object({ + uuid: z.string().min(1).max(64).optional(), + exercise_id: z.number().int().positive().optional(), + exercise_name: z.string().min(1).max(200).optional(), + sets: z.number().int().min(1).max(MAX_TARGET_SETS).optional(), + reps: target.optional(), + weight: target.optional(), + rest_sec: z.number().int().min(0).max(MAX_REST_SEC).optional(), + notes: z.string().max(MAX_NOTES_LENGTH).optional(), +}); + +export const EXERCISES_INPUT = z.array(EXERCISE_INPUT).max(MAX_TEMPLATE_EXERCISES); + +const EXERCISE_HELP = + 'Each exercise: exercise_id (from search_exercises) or exercise_name, sets ' + + `(1-${MAX_TARGET_SETS}, default 3), reps (a number or text such as "8-12"), weight ` + + "(optional, in the user's weight unit), rest_sec and notes (both optional)."; +export { EXERCISE_HELP }; + +/** An exercise this account can use: the shared library or one it made. */ +function _libraryExercise(userId, { id, name }) { + if (id != null) { + return db.prepare( + 'SELECT id, name FROM exercises WHERE id = ? AND deleted_at IS NULL AND (is_global = 1 OR created_by = ?)' + ).get(id, userId) || null; + } + return db.prepare( + `SELECT id, name FROM exercises + WHERE deleted_at IS NULL AND fold(name) = ? AND (is_global = 1 OR created_by = ?) + ORDER BY id ASC LIMIT 1` + ).get(foldText(name), userId) || null; +} + +/** + * The stored form of one exercise. `existing` is the stored exercise with + * the same uuid, when there is one: it is the base, and only what the caller + * sent is changed on it. Throws on an exercise_id the account can't use and + * on a new exercise that names nothing. + */ +export function toStoredExercise(userId, input, existing = null) { + const out = existing ? { ...existing } : { target_sets: 3, target_reps: '', target_weight: '', notes: '', sets: [] }; + if (input.exercise_id != null) { + const found = _libraryExercise(userId, { id: input.exercise_id }); + if (!found) throw new Error(`Exercise ${input.exercise_id} not found. search_exercises returns the exercise_id to use.`); + out.exercise_id = found.id; + out.exercise_name = found.name; + } else if (input.exercise_name != null) { + // A name alone: the library exercise of that name when there is one, so + // its history and records follow; else a free-text exercise, as a + // program imported from a spreadsheet has. + const found = _libraryExercise(userId, { name: input.exercise_name }); + if (found) { out.exercise_id = found.id; out.exercise_name = found.name; } + else { delete out.exercise_id; out.exercise_name = input.exercise_name.trim(); } + } else if (!existing) { + throw new Error('Each new exercise needs an exercise_id or an exercise_name.'); + } + if (input.sets != null) out.target_sets = input.sets; + if (input.reps != null) out.target_reps = String(input.reps); + if (input.weight != null) out.target_weight = String(input.weight); + if (input.rest_sec != null) out.rest_sec = input.rest_sec; + if (input.notes != null) out.notes = input.notes; + return out; +} + +/** One stored exercise, as the tools return it. */ +export function publicExercise(ex) { + return { + uuid: ex.uuid || null, + exercise_id: ex.exercise_id ?? null, + exercise_name: ex.exercise_name || null, + sets: ex.target_sets ?? null, + reps: ex.target_reps ?? null, + weight: ex.target_weight ?? null, + rest_sec: ex.rest_sec ?? null, + notes: ex.notes || null, + set_type: ex.set_type || null, + superset_id: ex.superset_id ?? null, + // Weeks 2 and later of a multi-week program, set in the app's editor. + // The tools change week 1 only and leave these as they are. + has_weekly_plan: Array.isArray(ex.weeks) && ex.weeks.some(Boolean), + }; +} + +export function publicTemplate(row) { + // As stored: an exercise saved without a uuid (a starter program's) shows + // uuid null. Stamping one here without saving it would hand out an id that + // is gone on the next read, and saving it would break the app's own first + // save of that day (issue #85, routes/templates.js). + const exercises = JSON.parse(row.exercises || '[]').filter(e => e && typeof e === 'object'); + return { + template_id: row.id, + program_id: row.program_id, + name: row.name, + day_label: row.day_label || null, + exercises: exercises.map(publicExercise), + }; +} + +export function publicProgram(row) { + return { + program_id: row.id, + name: row.name, + description: row.description || null, + goal: row.goal || 'general', + duration_weeks: row.duration_weeks || 1, + advance_mode: row.advance_mode || 'sessions', + on_complete: row.on_complete || 'hold', + }; +} + +/** + * A program the account may change, or an Error saying why not. One it + * can't see and one deleted read the same, as the routes answer them. + */ +export function changeableProgram(userId, programId) { + const access = programFor(programId, userId); + if (!access.canSee || access.program.deleted_at) throw new Error(`Program ${programId} not found.`); + if (!access.canChange) { + throw new Error(`Program ${programId} can't be changed: it was made by someone else (a coach, or a starter program).`); + } + return access.program; +} + +/** A live workout day of a program the account may change. */ +export function changeableTemplate(userId, templateId) { + const row = db.prepare('SELECT * FROM workout_templates WHERE id = ? AND deleted_at IS NULL').get(templateId); + const access = row ? programFor(row.program_id, userId) : null; + if (!row || !access.canSee || access.program.deleted_at) throw new Error(`Template ${templateId} not found.`); + if (!access.canChange) { + throw new Error(`Template ${templateId} can't be changed: its program was made by someone else (a coach, or a starter program).`); + } + return row; +} + +/** The newer-wins merge of the named fields of a row, for an edit made now. */ +export function mergeFields(table, existing, body) { + return applyToBody(null, existing, body, { ...syncOf(table), current: f => existing[f] }); +} + +/** + * Replace a day's exercise list with `inputs`, the way PUT /api/templates/:id + * saves one: stored exercises the list leaves out are deleted with a + * tombstone (so a device that still has them doesn't bring them back), ones + * it names by uuid are changed in place, and the rest are added. Runs inside + * the caller's transaction. Returns { exercisesJson, times }. + * + * A day none of whose exercises has a uuid yet (a starter program's) is + * replaced as a whole, which is what the merge does for the app's first save + * of such a day too (issue #85). + */ +export function replaceTemplateExercises(userId, template, inputs, timesJson) { + const stored = JSON.parse(template.exercises || '[]').filter(e => e && typeof e === 'object'); + const noIds = stored.length > 0 && stored.every(e => !e.uuid); + const serverExs = noIds ? stored : ensureExerciseUuids(stored); + const byUuid = new Map(noIds ? [] : serverExs.map(e => [e.uuid, e])); + const next = ensureExerciseUuids(inputs.map(input => { + const existing = input.uuid ? byUuid.get(input.uuid) : null; + if (input.uuid && !existing) throw new Error(`No exercise with uuid ${input.uuid} in template ${template.id}. get_program returns the uuids.`); + return toStoredExercise(userId, input, existing); + })); + const kept = new Set(next.map(e => e.uuid)); + const deletedUuids = noIds ? [] : serverExs.map(e => e.uuid).filter(u => !kept.has(u)); + + const tsKey = `template:${template.id}`; + const priorExTs = db.prepare( + `SELECT uuid FROM workout_tombstones WHERE user_id IS NULL AND date = ? AND kind = 'template_exercise'` + ).all(tsKey).map(r => r.uuid); + const priorSetTsByEx = {}; + for (const r of db.prepare( + `SELECT ex_uuid, uuid FROM workout_tombstones WHERE user_id IS NULL AND date = ? AND kind = 'template_set'` + ).all(tsKey)) (priorSetTsByEx[r.ex_uuid] = priorSetTsByEx[r.ex_uuid] || []).push(r.uuid); + + const r = mergeExercises(serverExs, next, deletedUuids, priorExTs, {}, priorSetTsByEx); + const insertTombstone = db.prepare( + `INSERT OR IGNORE INTO workout_tombstones (user_id, date, kind, ex_uuid, uuid, deleted_at) + VALUES (NULL, ?, 'template_exercise', '', ?, datetime('now'))` + ); + for (const uuid of r.newTombstoneExerciseUuids) insertTombstone.run(tsKey, uuid); + return { exercisesJson: JSON.stringify(r.merged), times: stampMerged(null, timesJson, ['exercises']) }; +} diff --git a/server/lib/mcp/tools/create-program.js b/server/lib/mcp/tools/create-program.js new file mode 100644 index 00000000..83c10ec6 --- /dev/null +++ b/server/lib/mcp/tools/create-program.js @@ -0,0 +1,55 @@ +/** + * MCP tool: create_program (write) + * + * Make a new, empty program owned by the caller (issue #154), as POST + * /api/programs does. Workout days are added with create_template. The + * program is not made active: the user picks that in the app. + */ +import { z } from 'zod'; +import db from '../../../db.js'; +import { + MAX_DESCRIPTION_LENGTH, MAX_NAME_LENGTH, MAX_PROGRAM_WEEKS, PROGRAM_GOALS, publicProgram, +} from '../_program-write.js'; +import { toolResult, toolError } from '../_util.js'; + +export function createProgramCore(userId, args = {}) { + const name = String(args.name || '').trim(); + if (!name) throw new Error('name is required.'); + const info = db.prepare( + `INSERT INTO programs (name, description, goal, created_by, visibility, duration_weeks, advance_mode, on_complete) + VALUES (?, ?, ?, ?, 'private', ?, ?, ?)` + ).run( + name, args.description || null, args.goal || 'general', userId, + args.duration_weeks || 1, args.advance_mode || 'sessions', args.on_complete || 'hold' + ); + const row = db.prepare('SELECT * FROM programs WHERE id = ?').get(info.lastInsertRowid); + return { ok: true, program: publicProgram(row) }; +} + +export function registerCreateProgram(server, { userId }) { + server.registerTool( + 'create_program', + { + title: 'Create Program', + description: + 'Create a new, empty program for the caller. Add its workout days with ' + + 'create_template. duration_weeks (1 by default) is how many weeks the ' + + "plan runs; advance_mode is how it moves to the next week ('sessions': " + + "after each week's workouts are done, the default; 'calendar': every 7 " + + "days); on_complete is what happens after the last week ('hold', the " + + "default, or 'repeat'). The program is not made active.", + inputSchema: { + name: z.string().min(1).max(MAX_NAME_LENGTH), + description: z.string().max(MAX_DESCRIPTION_LENGTH).optional(), + goal: z.enum(PROGRAM_GOALS).optional(), + duration_weeks: z.number().int().min(1).max(MAX_PROGRAM_WEEKS).optional(), + advance_mode: z.enum(['sessions', 'calendar']).optional(), + on_complete: z.enum(['hold', 'repeat']).optional(), + }, + }, + async (args) => { + try { return toolResult(createProgramCore(userId, args)); } + catch (e) { return toolError(e.message); } + } + ); +} diff --git a/server/lib/mcp/tools/create-template.js b/server/lib/mcp/tools/create-template.js new file mode 100644 index 00000000..683c1e94 --- /dev/null +++ b/server/lib/mcp/tools/create-template.js @@ -0,0 +1,56 @@ +/** + * MCP tool: create_template (write) + * + * Add a workout day to a program the caller made (issue #154), as POST + * /api/templates does: it goes after the program's last day. + */ +import { z } from 'zod'; +import db from '../../../db.js'; +import { ensureExerciseUuids } from '../../workout-merge.js'; +import { + EXERCISE_HELP, EXERCISES_INPUT, MAX_NAME_LENGTH, + changeableProgram, publicTemplate, toStoredExercise, +} from '../_program-write.js'; +import { toolResult, toolError } from '../_util.js'; + +export function createTemplateCore(userId, args = {}) { + const name = String(args.name || '').trim(); + if (!name) throw new Error('name is required.'); + const row = db.transaction(() => { + const program = changeableProgram(userId, args.program_id); + const exercises = ensureExerciseUuids((args.exercises || []).map(input => { + if (input.uuid) throw new Error("A new template's exercises take no uuid: they get one when saved."); + return toStoredExercise(userId, input); + })); + const maxIdx = db.prepare('SELECT MAX(order_index) as m FROM workout_templates WHERE program_id = ?').get(program.id); + const info = db.prepare( + 'INSERT INTO workout_templates (program_id, name, day_label, order_index, exercises) VALUES (?, ?, ?, ?, ?)' + ).run(program.id, name, args.day_label || null, (maxIdx?.m ?? -1) + 1, JSON.stringify(exercises)); + return db.prepare('SELECT * FROM workout_templates WHERE id = ?').get(info.lastInsertRowid); + })(); + return { ok: true, template: publicTemplate(row) }; +} + +export function registerCreateTemplate(server, { userId }) { + server.registerTool( + 'create_template', + { + title: 'Create Template', + description: + 'Add a workout day (template) to a program the caller made, after its ' + + 'last day. day_label is optional text shown with the name, such as ' + + '"Monday". ' + EXERCISE_HELP + ' Exercises can be left out and added ' + + 'later with update_template.', + inputSchema: { + program_id: z.number().int().positive(), + name: z.string().min(1).max(MAX_NAME_LENGTH), + day_label: z.string().max(MAX_NAME_LENGTH).optional(), + exercises: EXERCISES_INPUT.optional(), + }, + }, + async (args) => { + try { return toolResult(createTemplateCore(userId, args)); } + catch (e) { return toolError(e.message); } + } + ); +} diff --git a/server/lib/mcp/tools/delete-program.js b/server/lib/mcp/tools/delete-program.js new file mode 100644 index 00000000..061ad25b --- /dev/null +++ b/server/lib/mcp/tools/delete-program.js @@ -0,0 +1,74 @@ +/** + * MCP tools: delete_program and delete_template (destroy) + * + * Delete a program with all its workout days, or one workout day (issue + * #154), as DELETE /api/programs/:id and DELETE /api/templates/:id do: the + * same row delete, which synced devices learn about the way they learn about + * the app's own. Neither can be undone, so both need confirm: true on top of + * the server flag and the token scope (see routes/mcp.js). Workouts already + * logged from the program stay in the diary. + */ +import { z } from 'zod'; +import db from '../../../db.js'; +import { changeableProgram, changeableTemplate } from '../_program-write.js'; +import { toolResult, toolError } from '../_util.js'; + +export function deleteProgramCore(userId, programId) { + return db.transaction(() => { + const program = changeableProgram(userId, programId); + db.prepare('DELETE FROM programs WHERE id = ?').run(program.id); + return { ok: true, deleted: true, program_id: program.id, name: program.name }; + })(); +} + +export function deleteTemplateCore(userId, templateId) { + return db.transaction(() => { + const template = changeableTemplate(userId, templateId); + db.prepare('DELETE FROM workout_templates WHERE id = ?').run(template.id); + return { ok: true, deleted: true, template_id: template.id, program_id: template.program_id, name: template.name }; + })(); +} + +export function registerDeleteProgram(server, { userId }) { + server.registerTool( + 'delete_program', + { + title: 'Delete Program', + description: + 'Permanently delete a program the caller made, with all its workout ' + + 'days. Workouts already logged from it stay. Cannot be undone. ' + + 'Requires confirm: true.', + inputSchema: { + program_id: z.number().int().positive(), + confirm: z.boolean(), + }, + }, + async ({ program_id, confirm }) => { + if (!confirm) return toolError('Refusing to delete without confirm: true. This cannot be undone.'); + try { return toolResult(deleteProgramCore(userId, program_id)); } + catch (e) { return toolError(e.message); } + } + ); +} + +export function registerDeleteTemplate(server, { userId }) { + server.registerTool( + 'delete_template', + { + title: 'Delete Template', + description: + 'Permanently delete one workout day (template) of a program the ' + + 'caller made. Workouts already logged from it stay. Cannot be undone. ' + + 'Requires confirm: true.', + inputSchema: { + template_id: z.number().int().positive(), + confirm: z.boolean(), + }, + }, + async ({ template_id, confirm }) => { + if (!confirm) return toolError('Refusing to delete without confirm: true. This cannot be undone.'); + try { return toolResult(deleteTemplateCore(userId, template_id)); } + catch (e) { return toolError(e.message); } + } + ); +} diff --git a/server/lib/mcp/tools/get-program.js b/server/lib/mcp/tools/get-program.js new file mode 100644 index 00000000..c038bafc --- /dev/null +++ b/server/lib/mcp/tools/get-program.js @@ -0,0 +1,53 @@ +/** + * MCP tool: get_program + * + * One program with its workout days and every exercise's targets, for a + * caller that is about to change it (issue #154): list_programs gives the + * ids, this gives what update_program, update_template and delete_template + * work on. Reads what GET /api/programs/:id reads: a program the caller + * made, one a coach assigned, or a starter program. + */ +import { z } from 'zod'; +import db from '../../../db.js'; +import { programFor } from '../../program-access.js'; +import { publicProgram, publicTemplate } from '../_program-write.js'; +import { toolResult, toolError } from '../_util.js'; + +export function getProgramCore(userId, programId) { + const access = programFor(programId, userId); + if (!access.canSee || access.program.deleted_at) throw new Error(`Program ${programId} not found.`); + const templates = db.prepare( + 'SELECT * FROM workout_templates WHERE program_id = ? AND deleted_at IS NULL ORDER BY order_index ASC' + ).all(programId); + const active = !!db.prepare( + 'SELECT 1 FROM program_assignments WHERE program_id = ? AND assigned_to = ? AND active = 1' + ).get(programId, userId); + return { + ...publicProgram(access.program), + is_active: active, + // false for a coach's program or a starter program: the write tools refuse those. + can_edit: access.canChange, + templates: templates.map(publicTemplate), + }; +} + +export function registerGetProgram(server, { userId }) { + server.registerTool( + 'get_program', + { + title: 'Get Program', + description: + 'One program with its workout days (templates) in order and, for each, ' + + 'every exercise with its uuid, exercise_id, sets, reps, weight, rest_sec ' + + 'and notes. can_edit says whether the write tools may change it. ' + + 'list_programs returns the program_id to use.', + inputSchema: { + program_id: z.number().int().positive(), + }, + }, + async ({ program_id }) => { + try { return toolResult(getProgramCore(userId, program_id)); } + catch (e) { return toolError(e.message); } + } + ); +} diff --git a/server/lib/mcp/tools/index.js b/server/lib/mcp/tools/index.js index dee4f31f..44eaece9 100644 --- a/server/lib/mcp/tools/index.js +++ b/server/lib/mcp/tools/index.js @@ -20,6 +20,7 @@ import { registerGetExerciseProgress } from './get-exercise-progress.js'; import { registerSearchExercises } from './search-exercises.js'; import { registerListPrograms } from './list-programs.js'; import { registerGetActiveProgram } from './get-active-program.js'; +import { registerGetProgram } from './get-program.js'; import { registerGetBodyStat } from './get-body-stat.js'; import { registerGetBodyStats } from './get-body-stats.js'; import { registerListProgressPhotos } from './list-progress-photos.js'; @@ -30,7 +31,12 @@ import { registerStartProgramWorkout } from './start-program-workout.js'; import { registerLogBodyStat } from './log-body-stat.js'; import { registerAddProgressPhoto } from './add-progress-photo.js'; import { registerLogCardio } from './log-cardio.js'; +import { registerCreateProgram } from './create-program.js'; +import { registerUpdateProgram } from './update-program.js'; +import { registerCreateTemplate } from './create-template.js'; +import { registerUpdateTemplate } from './update-template.js'; import { registerDeleteWorkout } from './delete-workout.js'; +import { registerDeleteProgram, registerDeleteTemplate } from './delete-program.js'; export function registerReadTools(server, ctx) { registerGetWorkout(server, ctx); @@ -41,6 +47,7 @@ export function registerReadTools(server, ctx) { registerSearchExercises(server, ctx); registerListPrograms(server, ctx); registerGetActiveProgram(server, ctx); + registerGetProgram(server, ctx); registerGetBodyStat(server, ctx); registerGetBodyStats(server, ctx); registerListProgressPhotos(server, ctx); @@ -54,8 +61,14 @@ export function registerWriteTools(server, ctx) { registerLogBodyStat(server, ctx); registerAddProgressPhoto(server, ctx); registerLogCardio(server, ctx); + registerCreateProgram(server, ctx); + registerUpdateProgram(server, ctx); + registerCreateTemplate(server, ctx); + registerUpdateTemplate(server, ctx); } export function registerDestroyTools(server, ctx) { registerDeleteWorkout(server, ctx); + registerDeleteProgram(server, ctx); + registerDeleteTemplate(server, ctx); } diff --git a/server/lib/mcp/tools/update-program.js b/server/lib/mcp/tools/update-program.js new file mode 100644 index 00000000..bc90c2ce --- /dev/null +++ b/server/lib/mcp/tools/update-program.js @@ -0,0 +1,67 @@ +/** + * MCP tool: update_program (write) + * + * Change a program's own fields (issue #154), as PUT /api/programs/:id + * does: only the fields sent change, each one merged by the newer-wins rule + * the app's own edits follow (lib/newer-wins.js). Only a program the caller + * made can be changed (lib/program-access.js). + */ +import { z } from 'zod'; +import db from '../../../db.js'; +import { + MAX_DESCRIPTION_LENGTH, MAX_NAME_LENGTH, MAX_PROGRAM_WEEKS, PROGRAM_GOALS, + changeableProgram, mergeFields, publicProgram, +} from '../_program-write.js'; +import { toolResult, toolError } from '../_util.js'; + +const FIELDS = ['name', 'description', 'goal', 'duration_weeks', 'advance_mode', 'on_complete']; + +export function updateProgramCore(userId, programId, args = {}) { + const body = {}; + for (const f of FIELDS) if (args[f] !== undefined) body[f] = f === 'name' ? String(args[f]).trim() : args[f]; + if (body.name === '') throw new Error("name can't be empty."); + if (!Object.keys(body).length) throw new Error('Nothing to change: send at least one field.'); + const row = db.transaction(() => { + const existing = changeableProgram(userId, programId); + const times = mergeFields('programs', existing, body); + db.prepare( + `UPDATE programs SET name=COALESCE(?,name), description=COALESCE(?,description), + goal=COALESCE(?,goal), duration_weeks=COALESCE(?,duration_weeks), + advance_mode=COALESCE(?,advance_mode), on_complete=COALESCE(?,on_complete), + field_times=? WHERE id=?` + ).run( + body.name ?? null, body.description ?? null, body.goal ?? null, body.duration_weeks ?? null, + body.advance_mode ?? null, body.on_complete ?? null, times, programId + ); + return db.prepare('SELECT * FROM programs WHERE id = ?').get(programId); + })(); + return { ok: true, program: publicProgram(row) }; +} + +export function registerUpdateProgram(server, { userId }) { + server.registerTool( + 'update_program', + { + title: 'Update Program', + description: + "Change a program's name, description, goal, duration_weeks, " + + 'advance_mode or on_complete. Only the fields sent change. Works on a ' + + 'program the caller made (get_program can_edit: true), not on one a ' + + 'coach assigned or a starter program. Its workout days are changed ' + + 'with create_template, update_template and delete_template.', + inputSchema: { + program_id: z.number().int().positive(), + name: z.string().min(1).max(MAX_NAME_LENGTH).optional(), + description: z.string().max(MAX_DESCRIPTION_LENGTH).optional(), + goal: z.enum(PROGRAM_GOALS).optional(), + duration_weeks: z.number().int().min(1).max(MAX_PROGRAM_WEEKS).optional(), + advance_mode: z.enum(['sessions', 'calendar']).optional(), + on_complete: z.enum(['hold', 'repeat']).optional(), + }, + }, + async ({ program_id, ...args }) => { + try { return toolResult(updateProgramCore(userId, program_id, args)); } + catch (e) { return toolError(e.message); } + } + ); +} diff --git a/server/lib/mcp/tools/update-template.js b/server/lib/mcp/tools/update-template.js new file mode 100644 index 00000000..5abf3227 --- /dev/null +++ b/server/lib/mcp/tools/update-template.js @@ -0,0 +1,65 @@ +/** + * MCP tool: update_template (write) + * + * Change a workout day of a program the caller made (issue #154), as PUT + * /api/templates/:id does. The name and label merge by the newer-wins rule + * (lib/newer-wins.js). `exercises`, when sent, is the day's whole new list, + * in order: see replaceTemplateExercises in ../_program-write.js. + */ +import { z } from 'zod'; +import db from '../../../db.js'; +import { + EXERCISE_HELP, EXERCISES_INPUT, MAX_NAME_LENGTH, + changeableTemplate, mergeFields, publicTemplate, replaceTemplateExercises, +} from '../_program-write.js'; +import { toolResult, toolError } from '../_util.js'; + +export function updateTemplateCore(userId, templateId, args = {}) { + const body = {}; + if (args.name !== undefined) body.name = String(args.name).trim(); + if (args.day_label !== undefined) body.day_label = args.day_label; + if (body.name === '') throw new Error("name can't be empty."); + if (!Object.keys(body).length && !Array.isArray(args.exercises)) { + throw new Error('Nothing to change: send name, day_label or exercises.'); + } + const row = db.transaction(() => { + const existing = changeableTemplate(userId, templateId); + let times = mergeFields('workout_templates', existing, body); + let exercisesJson = null; + if (Array.isArray(args.exercises)) { + ({ exercisesJson, times } = replaceTemplateExercises(userId, existing, args.exercises, times)); + } + db.prepare( + 'UPDATE workout_templates SET name=COALESCE(?,name), day_label=COALESCE(?,day_label), exercises=COALESCE(?,exercises), field_times=? WHERE id=?' + ).run(body.name ?? null, body.day_label ?? null, exercisesJson, times, templateId); + return db.prepare('SELECT * FROM workout_templates WHERE id = ?').get(templateId); + })(); + return { ok: true, template: publicTemplate(row) }; +} + +export function registerUpdateTemplate(server, { userId }) { + server.registerTool( + 'update_template', + { + title: 'Update Template', + description: + 'Change a workout day (template): its name, day_label or exercises. ' + + 'Only what is sent changes. exercises, when sent, is the whole new ' + + 'list in order: an exercise sent with the uuid get_program returned ' + + 'is changed in place (fields left out keep their value), one sent ' + + 'without a uuid is added, and one left out of the list is removed. ' + + EXERCISE_HELP + ' Works on a program the caller made, not on one a ' + + 'coach assigned or a starter program.', + inputSchema: { + template_id: z.number().int().positive(), + name: z.string().min(1).max(MAX_NAME_LENGTH).optional(), + day_label: z.string().max(MAX_NAME_LENGTH).optional(), + exercises: EXERCISES_INPUT.optional(), + }, + }, + async ({ template_id, ...args }) => { + try { return toolResult(updateTemplateCore(userId, template_id, args)); } + catch (e) { return toolError(e.message); } + } + ); +}