Files
ia-fit/tests/server/mcp.test.js
T
2026-11-18 15:08:29 +01:00

231 lines
16 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { test } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { createMcp, PROPOSAL_SAVED } from "../../server/mcp.js";
import { createRelay } from "../../server/relay.js";
import { createEvent } from "../../app/domain/events.js";
import { foldEvents } from "../../app/domain/state.js";
import { EXAMPLE_PROGRAM } from "../../app/domain/example-program.js";
import { deriveKeys, encryptEvent, decryptEvent, generateSyncKey } from "../../app/domain/sync-crypto.js";
import { startServer, push, connect, rpc } from "./helpers.js";
const NOW = new Date("2026-11-18T12:00:00");
const device = "pc";
const PROFILE = { goal: "Force", context: "Maison", equipment: ["barre"], constraints: ["Pas de pareur"], heightCm: 180, sessionMinutes: 50 };
const squat = { id: "squat", name: "Squat", target: "4 × 8", tracking: /** @type {const} */ ("load"), loadKg: 60, seconds: null, plannedSets: 4, sets: [{ reps: 8, effort: /** @type {const} */ ("ok") }] };
function history() {
return [
createEvent("ProgramAdopted", { program: EXAMPLE_PROGRAM, source: "example" }, { device, at: "2026-11-01T10:00:00.000Z" }),
createEvent("ProfileUpdated", { profile: PROFILE }, { device, at: "2026-11-01T10:01:00.000Z" }),
createEvent("SessionLogged", { date: "2026-11-10", kind: "strength", ref: "A", name: "Séance A", warmup: null, exercises: [squat] }, { device, at: "2026-11-10T19:00:00.000Z" }),
createEvent("SessionLogged", { date: "2026-11-14", kind: "strength", ref: "A", name: "Séance A", warmup: null, exercises: [{ ...squat, loadKg: 62.5 }] }, { device, at: "2026-11-14T19:00:00.000Z" }),
createEvent("SessionLogged", { date: "2025-01-01", kind: "cardio", ref: "Vélo", name: "Vélo", warmup: null, exercises: [] }, { device, at: "2025-01-01T19:00:00.000Z" }),
createEvent("WeightRecorded", { date: "2026-11-01", kg: 82 }, { device, at: "2026-11-01T07:00:00.000Z" }),
createEvent("WeightRecorded", { date: "2026-11-15", kg: 81 }, { device, at: "2026-11-15T07:00:00.000Z" }),
];
}
/** Journal en mémoire (dossier temporaire), servi par un MCP sans HTTP. */
async function setup(events = history()) {
const relay = createRelay(fs.mkdtempSync(path.join(os.tmpdir(), "ia-fit-mcp-")));
const syncKey = generateSyncKey();
const keys = await deriveKeys(syncKey);
const blobs = await Promise.all(events.map((e) => encryptEvent(keys.encKey, e)));
// Un bloc d'une autre clé et un événement invalide : ignorés.
blobs.push(await encryptEvent((await deriveKeys(generateSyncKey())).encKey, events[0]));
blobs.push(await encryptEvent(keys.encKey, { id: "x", type: "Inconnu" }));
await relay.append(keys.journalId, keys.authToken, blobs);
const mcp = createMcp({ relay, publicUrl: "https://ia-fit.test", now: () => NOW });
/** @param {string} name @param {object} [args] */
const call = async (name, args = {}) => {
const r = /** @type {any} */ (await mcp.handle({ jsonrpc: "2.0", id: 7, method: "tools/call", params: { name, arguments: args } }, syncKey));
assert.equal(r.id, 7);
const text = r.result.content[0].text;
return { isError: !!r.result.isError, text, json: r.result.isError ? null : JSON.parse(text) };
};
/** Le journal tel que l'app le relirait. */
const journal = async () => {
const { events: stored } = await relay.read(keys.journalId, keys.authToken, 0);
const out = [];
for (const { blob } of stored) out.push(await decryptEvent(keys.encKey, blob).catch(() => null));
return out.filter(Boolean);
};
return { mcp, call, journal, syncKey };
}
test("initialize, tools/list, notifications et méthodes inconnues", async () => {
const { mcp, syncKey } = await setup();
const init = /** @type {any} */ (await mcp.handle({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18" } }, syncKey));
assert.equal(init.result.protocolVersion, "2025-06-18");
assert.match(init.result.instructions, /get_overview/);
assert.match(init.result.instructions, /https:\/\/ia-fit\.test\/ia\.md/);
assert.match(init.result.instructions, /proposition/);
const old = /** @type {any} */ (await mcp.handle({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2024-11-05" } }, syncKey));
assert.equal(old.result.protocolVersion, "2025-06-18");
assert.equal(await mcp.handle({ jsonrpc: "2.0", method: "notifications/initialized" }, syncKey), null);
const list = /** @type {any} */ (await mcp.handle({ jsonrpc: "2.0", id: 2, method: "tools/list" }, syncKey));
assert.deepEqual(list.result.tools.map((/** @type {any} */ t) => t.name), [
"get_overview", "get_program", "get_training_history", "get_exercise_progress", "get_body_weight",
"propose_program", "propose_session_change", "propose_wod", "propose_profile",
]);
assert.equal((/** @type {any} */ (await mcp.handle({ jsonrpc: "2.0", id: 3, method: "resources/list" }, syncKey))).error.code, -32601);
assert.equal((/** @type {any} */ (await mcp.handle({ jsonrpc: "2.0", id: 4, method: "tools/call", params: { name: "rm" } }, syncKey))).error.code, -32602);
});
test("lecture : vue d'ensemble, programme, historique, progression, poids", async () => {
const { call } = await setup();
const o = (await call("get_overview")).json;
assert.equal(o.today, "2026-11-18");
assert.equal(o.program.name, EXAMPLE_PROGRAM.name);
assert.deepEqual(o.profile, PROFILE);
assert.equal(o.mode, "progression");
assert.deepEqual(o.pendingProposals, []);
assert.equal(o.attendanceLast4Weeks.totals.strength, 2);
assert.equal(o.lastSession.date, "2026-11-14");
assert.deepEqual(o.lastWeight, { date: "2026-11-15", kg: 81 });
assert.ok(o.notes.some((/** @type {string} */ n) => /2 événement\(s\) illisibles/.test(n)));
assert.deepEqual((await call("get_program")).json.program, EXAMPLE_PROGRAM);
assert.equal((await call("get_training_history")).json.sessions.length, 2, "28 jours par défaut");
assert.equal((await call("get_training_history", { days: 1000 })).json.sessions.length, 3);
const progress = (await call("get_exercise_progress", { exercise_id: "squat" })).json;
assert.deepEqual(progress.points.map((/** @type {any} */ p) => p.loadKg), [60, 62.5]);
const none = (await call("get_exercise_progress", { exercise_id: "curl" })).json;
assert.deepEqual([none.points, none.knownExerciseIds], [[], ["squat"]]);
assert.equal((await call("get_exercise_progress", {})).isError, true);
const w = (await call("get_body_weight")).json;
assert.equal(w.weights.length, 2);
assert.ok(w.trend.kgPerWeek < 0);
});
test("propose_program : une proposition « ai » chiffrée dans le journal, que l'app relit", async () => {
const { call, journal } = await setup();
const before = (await journal()).length;
const program = { ...EXAMPLE_PROGRAM, name: "Programme revu" };
const r = await call("propose_program", { program, profile: { ...PROFILE, sessionMinutes: 40 }, reason: "Séances plus courtes" });
assert.equal(r.isError, false);
assert.equal(r.json.message, PROPOSAL_SAVED);
const events = /** @type {any[]} */ (await journal());
assert.equal(events.length, before + 1);
const proposed = events.at(-1);
assert.equal(proposed.type, "ProgramProposed");
assert.equal(proposed.device, "mcp");
assert.equal(proposed.data.source, "ai");
assert.equal(proposed.id, r.json.proposalId);
const state = foldEvents(events.filter((e) => e.v === 1 && e.device));
assert.equal(state.proposals[0].program.name, "Programme revu");
assert.equal(state.proposals[0].profile?.sessionMinutes, 40);
assert.equal(state.program?.name, EXAMPLE_PROGRAM.name, "le programme courant ne change pas");
// La vue d'ensemble la montre en attente.
assert.equal((await call("get_overview")).json.pendingProposals[0].reason, "Séances plus courtes");
});
test("propose_program invalide : refusé avec la liste des problèmes, rien n'est écrit", async () => {
const { call, journal } = await setup();
const before = (await journal()).length;
const r = await call("propose_program", { program: { name: "", sessions: [{ key: "A", name: "A", exercises: [{ ref: "inconnu", sets: 0, reps: "8", rest: 60 }] }] }, reason: "Essai" });
assert.equal(r.isError, true);
assert.match(r.text, /Proposition refusée/);
assert.match(r.text, /- programme : Le programme n'a pas de nom/);
assert.match(r.text, /'sets' doit être un entier/);
assert.equal((await call("propose_program", { program: EXAMPLE_PROGRAM, reason: "" })).isError, true, "raison obligatoire");
assert.match((await call("propose_program", { program: EXAMPLE_PROGRAM, profile: { goal: 3 }, reason: "x" })).text, /profil :/);
assert.equal((await journal()).length, before);
});
test("propose_session_change : fusion dans une copie du programme courant", async () => {
const { call, journal } = await setup();
const session = { name: "Séance A allégée", exercises: [{ ref: "squat", sets: 3, reps: "8", rest: 90 }] };
const r = await call("propose_session_change", { key: "A", session, reason: "Genou" });
assert.equal(r.isError, false);
const proposed = /** @type {any} */ ((await journal()).at(-1));
const sessions = proposed.data.program.sessions;
assert.equal(sessions.length, EXAMPLE_PROGRAM.sessions.length);
assert.deepEqual(sessions.find((/** @type {any} */ s) => s.key === "A"), { ...session, key: "A" });
assert.deepEqual(sessions.filter((/** @type {any} */ s) => s.key !== "A"), EXAMPLE_PROGRAM.sessions.filter((s) => s.key !== "A"));
// Nouvelle clé : séance ajoutée.
await call("propose_session_change", { key: "Z", session, reason: "Une de plus" });
assert.equal(/** @type {any} */ ((await journal()).at(-1)).data.program.sessions.length, EXAMPLE_PROGRAM.sessions.length + 1);
assert.equal((await call("propose_session_change", { key: "A", session: { ...session, key: "B" }, reason: "x" })).isError, true);
assert.equal((await call("propose_session_change", { key: "A", session: { name: "vide", exercises: [] }, reason: "x" })).isError, true);
});
test("propose_session_change : une séance d'étirements aux refs inventées devient une séance d'exercices génériques", async () => {
const { call, journal } = await setup();
const session = { name: "Mobilité", warmup: [], exercises: [
{ ref: "cat-cow", sets: 1, reps: "10", rest: 0, tracking: "none" },
{ ref: "pigeon-stretch", sets: 1, reps: "1 min / côté", rest: 0, tracking: "time" }] };
const r = await call("propose_session_change", { key: "M", session, reason: "Séance de mobilité" });
assert.equal(r.isError, false);
assert.equal(r.json.notices.length, 1);
assert.match(r.json.notices[0], /séance M, exercice n° 2 : « pigeon-stretch » n'est pas dans la bibliothèque.*« Pigeon stretch »/);
const added = /** @type {any} */ ((await journal()).at(-1)).data.program.sessions.find((/** @type {any} */ s) => s.key === "M");
assert.deepEqual(added.exercises[1], { name: "Pigeon stretch", sets: 1, reps: "1 min / côté", rest: 0, tracking: "time" });
assert.deepEqual(added.warmup, []);
assert.equal("notices" in (await call("propose_program", { program: EXAMPLE_PROGRAM, reason: "x" })).json, false);
});
test("propose_wod : WOD ponctuel ajouté hors rotation, clé choisie, WOD ponctuels faits retirés", async () => {
const wod = { name: "Cindy", format: { type: /** @type {const} */ ("amrap"), minutes: 20 },
exercises: [{ ref: "pull-up", sets: 1, reps: "5", rest: 0 }, { ref: "push-up", sets: 1, reps: "10", rest: 0 }, { ref: "bodyweight-squat", sets: 1, reps: "15", rest: 0 }] };
const program = { ...EXAMPLE_PROGRAM, sessions: [...EXAMPLE_PROGRAM.sessions, { ...wod, key: "J1", oneOff: true }] };
const events = [...history(), createEvent("ProgramAdopted", { program, source: "ai" }, { device, at: "2026-11-15T10:00:00.000Z" }),
createEvent("SessionLogged", { date: "2026-11-16", kind: "strength", ref: "J1", name: "Cindy", warmup: null, exercises: [],
wod: { format: wod.format, rx: true, seconds: null, rounds: 14, reps: 3, kg: null, capped: false } }, { device, at: "2026-11-16T19:00:00.000Z" })];
const { call, journal } = await setup(events);
const overview = (await call("get_overview")).json;
assert.deepEqual(overview.program.sessions.find((/** @type {any} */ x) => x.key === "J1"), { key: "J1", name: "Cindy", format: wod.format, oneOff: true, done: true, exercises: ["pull-up 1 × 5", "push-up 1 × 10", "bodyweight-squat 1 × 15"] });
const r = await call("propose_wod", { session: { ...wod, name: "Cindy (encore)", key: "A", oneOff: false }, reason: "Un AMRAP pour ce soir" });
assert.equal(r.isError, false);
assert.equal(r.json.key, "J2", "J1 a déjà servi");
const sessions = /** @type {any} */ ((await journal()).at(-1)).data.program.sessions;
assert.deepEqual(sessions.map((/** @type {any} */ s) => s.key), [...EXAMPLE_PROGRAM.sessions.map((s) => s.key), "J2"], "J1, faite, est retirée ; la séance A n'est pas touchée");
assert.equal(sessions.at(-1).oneOff, true);
assert.match((await call("propose_wod", { session: { name: "x", exercises: [] }, reason: "x" })).text, /'session.format' manquant/);
assert.match((await call("propose_wod", { session: { ...wod, format: { type: "amrap" } }, reason: "x" })).text, /format.minutes/);
});
test("propose_profile : le programme courant accompagné du nouveau profil ; sans programme, refusé", async () => {
const { call, journal } = await setup();
const r = await call("propose_profile", { profile: { ...PROFILE, constraints: ["Épaule droite"] }, reason: "Blessure" });
assert.equal(r.isError, false);
const proposed = /** @type {any} */ ((await journal()).at(-1));
assert.deepEqual(proposed.data.program, EXAMPLE_PROGRAM);
assert.deepEqual(proposed.data.profile.constraints, ["Épaule droite"]);
const empty = await setup([createEvent("WeightRecorded", { date: "2026-11-01", kg: 80 }, { device })]);
assert.match((await empty.call("propose_profile", { profile: PROFILE, reason: "x" })).text, /Aucun programme courant/);
assert.match((await empty.call("propose_session_change", { key: "A", session: {}, reason: "x" })).text, /Aucun programme courant/);
assert.equal((await empty.call("get_overview")).json.program, null);
});
test("de bout en bout en HTTP : jeton OAuth, outils, proposition déposée sur le relais", async () => {
const s = await startServer();
try {
const syncKey = generateSyncKey();
const keys = await deriveKeys(syncKey);
await push(s, keys.journalId, keys.authToken, await Promise.all(history().map((e) => encryptEvent(keys.encKey, e))));
const { tokens } = await connect(s, syncKey);
assert.equal((await rpc(s, "faux", "tools/list")).error, "invalid_token");
const overview = await rpc(s, tokens.access_token, "tools/call", { name: "get_overview", arguments: {} });
assert.equal(JSON.parse(overview.result.content[0].text).program.name, EXAMPLE_PROGRAM.name);
const proposed = await rpc(s, tokens.access_token, "tools/call", { name: "propose_program", arguments: { program: EXAMPLE_PROGRAM, reason: "Test" } });
assert.equal(proposed.result.isError, undefined);
const r = await s.fetch(`/api/journals/${keys.journalId}/events?after=${history().length}`, { headers: { authorization: "Bearer " + keys.authToken } });
const { events } = await r.json();
assert.equal(events.length, 1);
assert.equal(/** @type {any} */ (await decryptEvent(keys.encKey, events[0].blob)).type, "ProgramProposed");
// Notification : 202 sans corps.
const n = await s.fetch("/mcp", { method: "POST", headers: { authorization: "Bearer " + tokens.access_token }, body: JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }) });
assert.equal(n.status, 202);
assert.equal((await s.fetch("/mcp", { headers: { authorization: "Bearer " + tokens.access_token } })).status, 405);
} finally {
await s.close();
}
});