# openGym MCP server A [Model Context Protocol](https://modelcontextprotocol.io) bridge that lets an external LLM application (Claude Desktop, Cursor, Cline, Continue, etc.) read your openGym profile — routines, workouts, body-weight log, estimated 1RMs, and muscle balance — directly from your self-hosted `./data` directory. It is read-only, runs locally as a stdio process spawned by the LLM client, adds no new container, and requires no extra authentication. The LLM never sees passkeys, VAPID keys, or session secrets — it can only read the same `state-.json` files the openGym api already writes. The numbers it answers with are computed by the **same pure functions the React UI uses** (`frontend/src/lib/*.js`) — `estimate1RM`, `loadOfWorkouts`, `effectiveRoutine`, etc. — so a "what's my bench 1RM?" answer matches the Stats screen exactly. > Phase 1 of a multi-phase plan. Read-only today; long-lived token auth + write tools are > planned but not shipped yet. See **Roadmap** below. ## Quick start ### 1. Install ```bash cd mcp npm install ``` ### 2. Point it at your data The MCP server reads the same `./data` directory `docker compose up` creates. Pick the profile to answer for — its user id is in `./data/db.json` under `users[].id`: ```bash # single-user instance (the common self-hosted case) — auto-detected: node src/index.js # multi-user instance, or just to be explicit: OPENGYM_UID= OPENGYM_DATA=/path/to/openGym/data node src/index.js ``` ### 3. Register with your LLM client Add the server to your LLM client's MCP config. For Claude Desktop, edit `claude_desktop_config.json` (macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`): ```jsonc { "mcpServers": { "opengym": { "command": "node", "args": ["/absolute/path/to/openGym/mcp/src/index.js"], "env": { "OPENGYM_DATA": "/absolute/path/to/openGym/data", "OPENGYM_UID": "" // optional — auto-detected if you have one profile } } } } ``` For Cursor and other MCP-compatible clients, see the client's MCP docs — the same `command` + `args` + `env` shape is what every stdio MCP server expects. Restart the client; you should see the openGym tools appear with "serving profile \" on the server's stderr. ## Tools Eight read-only tools in v1: | Tool | What it answers | |---|---| | `list_routines` | What routines are saved in my profile? (names + exercise counts) | | `get_routine` | What does the Push Day routine prescribe? (sets/reps/weight per exercise) | | `get_week_plan` | What's on my plan this week, including today with any date-specific override? | | `list_workouts` | Recent sessions — newest first, with dates, sets done/planned, volume, duration, PRs. | | `get_workout` | Full set-by-set breakdown of one date's session. | | `get_bodyweight` | Weigh-ins with the latest weight, the goal line, and deltas vs goal. | | `estimate_1rm` | All-time best 1RM for an exercise + the trend, or a PR table across all exercises. | | `muscle_balance` | Which muscles I've trained this week/month/all-time, ranked + which I've neglected. | Each tool returns JSON the LLM can format as it likes; structured fields (sets, dates, levels) are pre-formatted into human-readable labels in `src/labels.js` so the LLM doesn't need to re-interpret them. ## How it reuses the training logic openGym deliberately keeps its training logic in pure functions under `frontend/src/lib/` with unit tests next to them (see `CONTRIBUTING.md` — "Training logic gets a unit test"). The MCP server imports those files directly as Node ESM and calls the same functions the UI does: ``` mcp/src/tools.js └── list_workouts handler ──▶ frontend/src/lib/history.js (workoutVolume, setsDone) └── estimate_1rm handler ──▶ frontend/src/lib/onerm.js (best1RM, e1rmSeries) └── muscle_balance ──▶ frontend/src/lib/muscles.js (loadOfWorkouts, rankOf, levelsOf) └── get_week_plan ──▶ frontend/src/lib/history.js (effectiveRoutine, effectiveRoutineId) ``` The one lib file that wasn't Node-safe was `i18n.js` (it used Vite's `import.meta.glob`) — split into `i18n-core.js` (pure, Node-safe) + `i18n.js` (Vite/React-specific bits, re-exports from core). `exercises.js` got a one-line guard against `import.meta.env` being undefined in plain Node. No new dependencies landed in `frontend/`, no public exports changed. ## Design constraints honoured - **One runtime dependency beyond the MCP SDK:** none. `mcp/package.json` declares only `@modelcontextprotocol/sdk` + its transitive `zod`. No database driver, no HTTP framework. - **No new container.** stdio transport is spawned by the LLM client; nothing to add to `docker-compose.yml`. - **No new auth.** The filesystem is the boundary — same as `docker compose` running on the user's box. The MCP server only sees what its host process can already see. - **No telemetry, no network.** Reads `./data/*.json` and exits when the LLM client disconnects. Matches the openGym ethos from `README.md`. - **State-On-Disk source of truth.** Uses `fs.watch` to pick up sessions the web UI just finished, with an mtime fallback for platforms where watchers are flaky. ## Tests ```bash cd mcp && npm test ``` Tool-layer tests (32 of them) seed state from `frontend/src/lib/demoSeed.js` — the same deterministic fixture the public demo deployment runs on. The pure lib functions themselves already have 92 tests of their own in `frontend/src/lib/*.test.js`. Three things the suite is deliberate about: - **Pinned fake time.** `vi.useFakeTimers({ now: new Date('2026-07-27T12:00:00Z'), toFake: ['Date'] })` freezes "today" to a Monday so date-dependent tools (`get_week_plan`, `muscle_balance`) see consistent values. `toFake: ['Date']` only mocks the Date object — `fs.watch`, `setTimeout` etc. keep working with the real event loop. - **Real numeric assertions** for a representative case per tool: hand-computed Epley 1RM (`152.5×12 → 213.5`), hand-computed body-weight delta (`78.5 − 77 = 1.5`), exact workout volume (`18500` kg). Structure-only assertions ("est > 0") are kept for the cases where the pure lib has its own tests already. - **Negative cases.** Empty state, missing routine, missing workout, reversed date range, no goal set, zero-workout `muscle_balance`, fresh-account no-state fallback for every tool. ## Mutation testing ```bash cd mcp && npm run mutation:test ``` Uses [Stryker](https://stryker-mutator.io) to mutate `src/state.js`, `src/labels.js` and `src/tools.js` (the three MCP-only modules — the reused pure lib in `frontend/src/lib/` is excluded since it has its own 92-test vitest suite). Config lives at `.stryker.conf.json`. **Run mode:** `inPlace: true`. Stryker mutates files where they live (so the test file's relative imports `../../frontend/src/lib/*.js` keep resolving), keeps a backup in `.stryker-tmp/backup-*/` during the run, and restores on exit — verified: after the run, `git diff` shows no changes and all tests still pass. If Stryker is killed hard (SIGKILL, power loss) the next run restores from the backup before mutating again. **Baseline (first run, 847 mutants):** | File | Score | Killed | Survived | No cov | |---|---:|---:|---:|---:| | `state.js` | 3.92% | 6 | 26 | 121 | | `labels.js` | 23.64% | 13 | 25 | 17 | | `tools.js` | 49.14% | 314 | 279 | 46 | | **Total** | **39.32%** | 333 | 330 | 184 | The 39% baseline is honest about how much of the *handler* logic the test suite genuinely exercises — many of the survivors are zod schema declarations (e.g. `period: z.enum(['week', 'month', 'all'])`) which mutation-testing finds hard to kill without testing the SDK's validation layer that the unit suite deliberately bypasses. Treat the score as a lower bound: every "no cov" mutant is a code path the suite hasn't even reached; each is a TODO on its own. Iterate; aim for 70%+ before the MCP server moves from v0.1 to v1. Report at `mcp/reports/mutation/mutation.html` (open in a browser, click any file to see survived mutants inline). ## Roadmap - **Done (Phase 1):** read-only stdio, 8 tools, direct `./data` access. - **Phase 1.5:** `progression_next` (what does the policy prescribe next?) + `search_exercises` (search the catalog). No new deps; small surface area. - **Phase 2:** read+write over stdio. Requires a long-lived token auth path minted from the admin dashboard (new `./data/tokens.json`) and a write-lock against the web UI's read-modify- write of `state-.json`. Tools: `log_workout`, `add_bodyweight`, `edit_routine`, `assign_weekday`, `override_day`. - **Phase 3:** Streamable HTTP transport, opt-in 4th container in `docker-compose.yml`. Same tool implementations, second transport — the MCP SDK supports both behind one tool registration. ## License AGPL-3.0-or-later, same as openGym.