Skip to main content
Glama
chess-mcp

chess-mcp

by T145
README.md
# chess-mcp

A local chess web app **and** MCP server for humans vs LLMs and LLM vs LLM games.

- Open a board in the browser, play moves, watch games update live.
- Invite any MCP-capable agent (Cline, Claude Code, etc.) into the other seat with one copy-paste prompt.
- Agents use **Streamable HTTP** MCP tools to join, wait for your move, and reply.
- Two agents can play each other while you spectate in real time.
- Finished games get a Stockfish review: accuracy, move labels, and an eval bar.
- Everything runs on `127.0.0.1`; there is no cloud dependency and no account system.

## Requirements

- Node.js **20.19+** (Node 24 recommended)
- pnpm **11+**

## Quick start

```bash
pnpm install
pnpm dev
```

Open **http://127.0.0.1:3000**.

For a production-style run:

```bash
pnpm build
pnpm start
```

`pnpm start` serves the built React app, the REST API, the WebSocket, and the MCP
endpoint from one process.

### CLI options

```text
chess-mcp [options]

--port <number>   Port to listen on (default: 3000, env: PORT)
--data-dir <dir>  Directory for saved games, courses, the engine, and runtime assets (env: CHESS_MCP_DATA_DIR)
--engine <path>   Use a local Stockfish binary (env: CHESS_MCP_ENGINE)
--engine-depth <n>  Analysis depth per position (default: 14)
--no-engine-download  Never download Stockfish, piece themes, or opening data automatically
--no-courses      Disable the course-authoring MCP endpoint and course storage
--dev             Serve the React app with Vite middleware (HMR, no build)
-h, --help        Show help
```

The server always binds to `127.0.0.1`. Open the printed URL in a browser.

### Saved games

Games are written to disk after every change (create, join, move, draw, resign),
so the lobby is restored the next time the server starts. Each game is a small
JSON file under `<data-dir>/games/<game-id>.json`; completed reviews are stored
next to them under `<data-dir>/reviews/<game-id>.json`, and authored courses
under `<data-dir>/courses/<course-id>.json` with learner progress under
`<data-dir>/course-progress/<course-id>.json`. Downloaded assets live beside them:
`engine/`, `themes/`, and `openings/`.

Default locations:

| Platform | Directory |
| --- | --- |
| Windows | `%USERPROFILE%\Saved Games\chess-mcp` |
| macOS | `~/Library/Application Support/chess-mcp` |
| Linux | `$XDG_DATA_HOME/chess-mcp` (default `~/.local/share/chess-mcp`) |

Override the location with `--data-dir <path>` or the `CHESS_MCP_DATA_DIR`
environment variable. Seat ownership survives restarts: only the SHA-256 hash
of each seat token is saved, and the original token keeps working. Deleting a
game removes its saved file.

### Piece themes

The sidebar **Themes** page switches the piece set on every board and remembers the
choice in `localStorage`. **Default** uses react-chessboard's built-in Cburnett pieces
(CC BY-SA 3.0, via Wikimedia Commons).

Theme management is centralized in `src/shared/themes.ts`, which defines the
built-in theme plus 51 runtime sets: 10 permissively licensed Lichess sets, 40
Chess.com sets, and Neo Angle. The picker loads `/api/themes` and polls while
the page is open, so server-managed sets appear as they become available.

All non-default sets are downloaded at runtime into
`<data-dir>/themes/<theme-id>/` and served from `/theme-assets/...`. The download
starts with the server when automatic downloads are enabled and runs alongside
the Stockfish install hook. Passing `--no-engine-download` disables Stockfish,
theme, and opening-book downloads.

The Lichess sets use Apache-2.0, CC0-1.0, CC BY 4.0, CC BY-SA 4.0, or MIT; the
Chess.com and Neo Angle sets are local-only and labelled “All rights reserved”.
Each catalog entry carries its author, license, and source URL, which the picker
displays. `Classic` is excluded because it duplicates Default; `Icy Sea` is
excluded because its CDN files are white silhouette/mask images.

## Play against an LLM

1. Click **New game**.
2. Enter your name, pick **White** (or Black), and choose a time control (or **No clock**).
3. On the game page, open **Invite a player** and copy the **Agent prompt** for the open seat.
4. Give that prompt to an MCP-enabled agent that has the `chess` server configured.
5. Play in the browser. The agent blocks on `wait_for_move`, receives your move, and replies.
6. The board, move list, draw offers, and result update over WebSocket for every spectator.

Joined the wrong colour? Click **Swap colors** on the game page (or on the lobby card)
before the first move: both seats exchange, each player keeps their own seat token,
and the PGN tags/board orientation follow automatically. Nothing needs recreating.

### Time controls

Games can carry a clock, using the usual ranked presets:

| Category | Presets |
| --- | --- |
| Bullet | `1+0`, `1+1`, `2+1` |
| Blitz | `3+0`, `3+2`, `5+0` |
| Rapid | `10+0`, `10+5`, `15+10` |
| Daily | `1d`, `3d`, `7d` |

Pass `timeControl` (REST) or `time_control` (MCP) with the preset id; omit it for an
untimed game. The clock is enforced on the server: the side to move is charged for its
thinking time, the increment is added after each move, and when a bank reaches zero the
game ends immediately with `phase: "timeout"`, the opponent as winner, and a
`1-0`/`0-1` PGN result. Both clocks are shown next to each player and printed in MCP
tool output. Daily presets behave as "N days per move": the bank is capped at the preset
so time never accumulates between moves. Clocks are saved with the game and resume with
the saved banks after a restart (downtime is not charged).

### MCP client configuration

```json
{
  "mcpServers": {
    "chess": {
      "type": "streamableHttp",
      "url": "http://127.0.0.1:3000/mcp"
    },
    "chess-courses": {
      "type": "streamableHttp",
      "url": "http://127.0.0.1:3000/mcp/courses"
    }
  }
}
```

The two servers share the same in-process state but expose **disjoint tool
lists**. `/mcp` contains only game tools; `/mcp/courses` contains only course
authoring/discovery tools. An agent that should play on its own merit can be
configured with `/mcp` alone, so it cannot discover or consult local lesson
material during a game. Only enable `chess-courses` for the agent that writes
courses.

For a strict game-only server, start with `--no-courses` (or
`CHESS_MCP_NO_COURSES=1`): `/mcp/courses` then returns `503`, no course files are
read or written, and the process cannot serve lesson material at all.

The endpoint uses **MCP Streamable HTTP** (the current transport). MCP's old
standalone HTTP+SSE transport is not used. The browser's live updates use a
separate WebSocket at `/ws`.

The `type` field is required. Clients treat a URL-only entry (`{"url": ...}`)
as the legacy SSE transport, open `GET /mcp` expecting an event stream, get
`405 Method Not Allowed`, and report the server as unavailable. Cline accepts
`"type": "streamableHttp"` (equivalently `"http"`); Claude Code and VS Code
call the same transport `"http"`. Clients that default to a ~60s tool timeout
should raise it (for example `"timeout": 150`) because `wait_for_move` can
long-poll for up to 120 seconds.

### Agent loop

```text
Use the chess MCP server at http://127.0.0.1:3000/mcp.
Join game <id> as <seat> with a name of your choice, and keep the seat_token
returned by join_game. Then loop:
  1. wait_for_move(game_id="<id>", seat_token="<token>")
  2. if it is your turn, make_move(game_id="<id>", move="<SAN or UCI>",
     seat_token="<token>", note="<why you chose it>")
Repeat until the game ends.
```

### Move notes

`make_move` takes an optional `note` (up to 500 characters). It is stored with the move and
written into the PGN as a `{comment}`:

```text
1. e4 {Controls the centre; watch ...d5} e5 2. Nf3 {Develops, eyes d5}
```

Notes are private while the game is running. An agent only receives its **own** notes —
`make_move` echoes the note back, and `get_game` with your `seat_token` returns your notes as
`Last move note: …` and as PGN comments. The opponent's notes are withheld from
`wait_for_move`/`get_game`, and the web interface shows none at all. A hotseat game (both
seats open) has a single operator, so that operator reads all of its own notes. Once the game
ends every note becomes public, in the web move list and in the PGN.

Writing the plan down before moving is a cheap check: it forces the threats and the
piece you are about to expose into the sentence, which is exactly where hasty moves go
wrong. Agents should send a note on every move, even a short one.

Seat tokens are returned once by `create_game`/`join_game`. Keep them in the
conversation and pass them on every mutating tool call. In a hotseat game
(both seats open) tokens are not required.

## Opening courses (authoring)

Courses live beside games but are a separate aggregate: no seats, clock, or
result. The opening dataset is now exposed in two shapes: the existing
position-keyed **book** (for live/review book labels) and a **catalog** of named
lines (ECO, name, SAN moves) used to seed a course from real theory. Both come
from the same pinned download; the catalog is cached as
`<data-dir>/openings/<tag>/catalog.tsv`.

Courses are authored over the **separate** `/mcp/courses` endpoint:

| Tool | Purpose |
| --- | --- |
| `list_openings` | Search the catalog by ECO code or name; each result shows the colour the opening is normally learned as. |
| `get_opening_line` | Resolve an ECO/name to its SAN line and main perspective. |
| `create_course` | Create a draft (optional opening, learner colour, title). The learner colour defaults to the opening's perspective (Black for the Caro-Kann) and can be overridden. Returns a course id and author token. |
| `add_lesson` | Append a lesson: `startFen`, mainline `moves`, prompts per ply (`steps`), optional `variations`, optional `side`, and `history`. Every move is validated with chess.js. |
| `add_quiz` | Append a `move` quiz (accepted SAN in a FEN) or `choice` quiz (2–8 options, one answer). Use `wrongFeedback` and per-option `feedback` to explain incorrect answers. |
| `publish_course` | Mark the course ready; requires at least one lesson. |
| `set_course_history` | Replace the course-level historical context shown in the History tab. |
| `get_course` / `list_courses` | Read the summary and full JSON. |
| `validate_course` | Non-fatal gaps: no lessons/quizzes, missing explanations, steps asking about the opponent’s move, custom start positions. |

Authoring loop for an agent:

```text
Use the chess course MCP server at http://127.0.0.1:3000/mcp/courses.
list_openings(query="Najdorf"), then create_course(opening="...").
Add 1–3 lessons with add_lesson, each with a mainline, a few prompted steps,
optional variations, lesson.history, and an optional per-lesson side. Add move
and choice quizzes with add_quiz; use `wrongFeedback` and per-option `feedback`
to explain wrong answers. Set course history with set_course_history, call
validate_course, then publish_course with the author token.
```

The web picker and `create_course` both default `side` to the opening's main
perspective: named defenses and Black gambits (Caro-Kann, Sicilian, Benko) are
learned as Black, while openings such as the Ruy Lopez or Italian Game are
learned as White. That inference looks at the family name before any variation
colon, so "Ruy Lopez: Morphy Defense" stays a White course. Pass `side`
explicitly to learn the other colour.

The picker opens in **Main openings** mode, which searches only family-level
names such as "Queen's Gambit" or "Caro-Kann Defense" and hides named sidelines.
Switching to **All variations** restores the advanced ECO/name search over the
complete catalog. When the opening field is left empty, the dialog shows its
"Learn as" selector so a free-form course can still be authored for either
colour; selecting a catalog opening hides the selector and infers the side.

Courses are saved as `<data-dir>/courses/<course-id>.json` (atomic writes, like
games) and reloaded at startup. Only the SHA-256 hash of the author token is
stored. Agent-authored content is bounded and validated: illegal SAN, bad FENs,
duplicate ids, unknown lesson references, and oversized collections are
rejected; text is sanitised and capped.

The course-authoring endpoint intentionally has **no** game tools (`make_move`,
`wait_for_move`, `get_game`, etc.), and the game endpoint has no course tools.
A playing agent therefore cannot read local lesson material mid-game.

### Learning a course in the browser

1. Open **Classroom** in the retractable sidebar and click **New course** (or use
   the sidebar's **New** menu).
2. Enter your name, choose **White** or **Black**, and search the opening catalog
   by name or ECO code. Leaving the opening empty creates a free-form course.
3. **Create course** opens `/course/<id>`. While the course is a draft, the page
   shows a copyable **author prompt** and stores the author token in this browser.
4. Give the prompt to an agent configured with `chess-courses`. Its `add_lesson`
   and `add_quiz` calls appear live on the page through the WebSocket; no reload.
5. When the course is ready, the agent calls `publish_course` (or the creator can
   press **Publish** in the draft banner, which uses the stored token).

On the course page:

- The board shows the current lesson position. When a step is prompted, play the
  move on the board. Accepted moves advance the mainline and the coach replies
  automatically; rejected moves snap back with feedback (and an optional hint
  arrow). The hint button sits under the side panel with previous/next lesson
  controls; its tooltip explains that it shows the move on the board.
- Lessons may set their own `side`, so a Black course can default to Black's
  perspective and switch to White for an aggressive line. Without an override the
  board uses the course's learner colour; **Flip** is still there.
- **Steps** lists every prompt with a checkmark when completed; click one to
  replay from that ply.
- **Questions** appear inline at the end of a lesson and unlock only after every
  step is complete; quizzes without a `lessonId` appear after the final lesson as
  a course review. Move quizzes are answered on the board, multiple-choice
  answers are graded in the panel, and the result (the correct explanation, or
  the author's feedback for a wrong option) appears inside the answered
  question. The correct option/answer is highlighted, and a move answer stays
  on the board with its from/to squares lit so you can see exactly which move
  was graded. **Try another move** returns the board to the question position.
- **History** shows per-lesson historical context and the course-level history.
  The author provides lesson history in `add_lesson` and course history with
  `set_course_history`.

Progress is stored per learner at `<data-dir>/course-progress/<course-id>.json`.
A stable learner id lives in `localStorage`, so the same browser resumes where it
left off; the selected lesson and ply are also remembered locally. Attempts are
idempotent for steps and counted for quizzes. Classroom cards show **Start
course**, then **Continue** once the course has any completed step or quiz
attempt. Deleting a course (the trash icon on the course page) removes its
progress as well.

## Game review

When a game ends, the server analyses every position with Stockfish and stores a
review alongside the game. Open the **Review** tab on the game page (or call the
`review_game` MCP tool) to see:

- accuracy for both players, plus counts of book / brilliant / great / best /
  excellent / good / inaccuracy / mistake / blunder moves;
- the opening name and ECO code when the game followed known theory;
- an evaluation graph and a **vertical eval bar to the left of the board**;
- move badges plus the complete annotated move list; click any move (or use the
  navigation buttons) to step through the game on the board, with the clock as
  it stood after that move. The board highlights the played move in the badge's
  colour, pins the badge to the destination square's top-right corner, and draws
  a Chess.com-style green arrow for the engine's recommended move.

### Engine setup

The server looks for Stockfish in this order:

1. `--engine <path>` or `CHESS_MCP_ENGINE`;
2. `stockfish` on `PATH`;
3. common install folders (`/usr/games`, `/usr/bin`, `/usr/local/bin`,
   `/opt/homebrew/bin`, `%LOCALAPPDATA%\Stockfish`, `Program Files\Stockfish`);
4. a previously downloaded binary in `<data-dir>/engine/sf_19/`.

If nothing is found, the server automatically downloads the official
**Stockfish 19** release from GitHub on first boot (about 80 MB, universal binary
that detects AVX2/AVX-512 etc. itself). Downloads are pinned to the release asset
name, byte size, and SHA-256 digest, verified before the binary is extracted and
run. The install is background work: the web app and MCP endpoint start
immediately, and review jobs queue until the engine is ready. Pass
`--no-engine-download` to disable Stockfish, theme, and opening-book downloads,
and use `--engine` for a local build.

The engine is GPL-3.0 software and is **not** bundled in the npm package: it is
fetched from the official release (or supplied by you) into your data directory.
The project itself stays Apache-2.0.

Analysis uses depth 14 and MultiPV 2 by default, one review at a time. Labels are
heuristic (win-probability loss, only-move detection, and a material-sacrifice
check for brilliant moves), not a clone of Chess.com's proprietary algorithm.

### Opening book

Moves that follow known opening theory are labelled **Book** (the brown book
badge), and the game shows the opening name and ECO code while it is still in
theory. Detection runs without the engine, so the Moves tab shows it during play
and the Review tab repeats it for finished games.

The data is a pinned snapshot of
[lichess-org/chess-openings](https://github.com/lichess-org/chess-openings)
(CC0-1.0): 3,865 lines folded into 7,982 position-keyed entries. It is
downloaded on first boot into `<data-dir>/openings/<tag>/` as five TSV files,
each pinned by byte size and SHA-256 in `src/openings/release.ts` and verified
before use. The derived position index (`book.tsv`) is cached beside them, so
later boots read one file instead of replaying the lines. `pnpm openings:check`
re-downloads the dataset into a temporary directory and spot-checks the Ruy
Lopez.

A game is "in book" only while *every* ply so far is in the dataset, starting
from the standard initial position. Positions are matched by FEN (move counters
ignored), so transpositions work, and the name shown is the deepest named
position reached. Games started from a custom FEN are never labelled. Like the
move labels, this is a dataset lookup rather than Chess.com's proprietary
opening book.

Book moves are displayed like any other classified move: the from/to squares are
tinted in the book colour and the brown badge sits on the destination square.
When a move leaves theory, the board draws a brown "book move" arrow at the
continuation the dataset considers main (it prefers a named continuation, then
the branch with the most follow-up theory, since ECO data has no move
frequencies). That arrow replaces the green engine arrow on that ply.

The ECO code next to the opening name is a discreet link (dotted underline) to
the Lichess analysis board at the last book position. Its opening explorer is
built from the same dataset, so it lists the position's continuations, results,
and games; nothing is requested until you click it.

Reviews are cached, so a review saved before the dataset existed would keep its
old labels. Opening labels are therefore refreshed lazily when a cached review is
opened — book moves keep the engine's verdict in `baseQuality`, so re-labelling
never needs another Stockfish run. `pnpm reviews:relabel` does the same for every
saved review at once.

The move labels in the web app use Chess.com's published 18×18 classification
badge SVGs, mirrored from
`https://www.chess.com/bundles/web/images/color-icons/` into
`web/public/badges/` so reviews render without a network connection. All 12
classification assets are included — the ten used by the app (book, brilliant,
great find, best, excellent, good, inaccuracy, mistake, blunder, forced) plus the
unused miss and missed-win. The UI falls back to its own glyph if an asset is
missing. Badge artwork remains Chess.com's, is not covered by this project's
Apache-2.0 license, and is bundled for local use only.

## MCP tools

The game endpoint is `/mcp`; course authoring tools live separately on
`/mcp/courses` (see [Opening courses](#opening-courses-authoring)).

| Tool | Purpose |
| --- | --- |
| `create_game` | Create a game and claim white, black, or no seat (`none`), with an optional `time_control` preset. Returns a game id and seat token. |
| `join_game` | Claim an open seat. Returns a seat token. |
| `list_games` | List active games with players, turn, status, and last move. |
| `get_game` | Full state: ASCII board, FEN, PGN, seats, turn/check/result, legal moves. Pass `seat_token` to include your own move notes. |
| `make_move` | Play SAN (`Nf3`, `O-O`, `e8=Q`) or UCI (`e2e4`, `e7e8q`). Optional `note` records your reasoning privately until the game ends. Enforces turn and seat token. |
| `wait_for_move` | Pass your seat token: returns immediately when it is your turn, otherwise long-polls until the opponent moves, the game ends, or a timeout (1–120s) expires. |
| `draw` | `offer`, `accept`, or `decline` a draw. |
| `resign` | Resign. |
| `review_game` | Analyze a finished game with Stockfish and return accuracy, move labels, and key moments. Waits briefly for the engine download/analysis. |

Game state includes a text board, so an agent can play without extra round trips:

```text
Game 3f9c2a1b
White: Alice (human)
Black: Claude (llm)
Status: Black to move.
Last move: e4 (e2e4)

  +------------------------+
8 | r n b q k b n r |
7 | p p p p . p p p |
...
    a b c d e f g h

FEN: ...
Legal moves (20): a6, a5, ...
```

## HTTP API (used by the web app)

| Method + path | Purpose |
| --- | --- |
| `GET /api/health` | Health and active game count |
| `GET /api/themes` | Theme catalog plus local asset download status |
| `GET /theme-assets/:themeId/:file` | Runtime theme piece images (`wK.svg` or `wK.png`) |
| `GET /api/games` | Public game list |
| `POST /api/games` | Create a game (`name`, `color`: white, black, random, or none; optional `timeControl` preset id) |
| `GET /api/games/:id` | Public game state |
| `POST /api/games/:id/join` | Claim `{ name, seat }` |
| `POST /api/games/:id/swap-seats` | Exchange the two seats `{ token }` — only before the first move |
| `POST /api/games/:id/moves` | Play `{ move, token? }` |
| `POST /api/games/:id/draw` | `{ action, token?, seat? }` |
| `POST /api/games/:id/resign` | `{ token?, seat? }` |
| `GET /api/engine` | Engine status: available / installing / unavailable / failed, download progress, depth |
| `POST /api/engine/install` | Retry the automatic Stockfish install |
| `GET /api/openings` | Opening-book status: phase, position count, data provenance |
| `GET /api/openings/book` | Position index as text (`ETag`/`304` aware); `503` until downloaded |
| `GET /api/openings/catalog` | Named opening lines as text (`ETag`/`304` aware); `503` until built |
| `POST /api/openings/install` | Retry the opening-book download |
| `GET /api/games/:id/review` | Review state, loading a saved review if present |
| `POST /api/games/:id/review` | Start (or reuse) a review; `400` while the game is running |
| `DELETE /api/games/:id` | Delete a game |
| `GET /api/courses` | List courses; add `?learnerId=…` to include non-empty progress |
| `POST /api/courses` | Create a human-authored course (`name`, `side`, optional `title`/`description`/`opening`) |
| `GET /api/courses/:id` | Full course state |
| `POST /api/courses/:id/publish` | Publish with the author token `{ token }` |
| `DELETE /api/courses/:id` | Delete a course and its progress |
| `GET /api/courses/:id/progress?learnerId=…` | Per-learner completed steps and quiz counts |
| `POST /api/courses/:id/lessons/:lessonId/attempt` | Grade a step move `{ learnerId, ply, move }` |
| `POST /api/courses/:id/quizzes/:quizId/answer` | Grade a quiz answer `{ learnerId, answer }` |
| `GET /ws` | WebSocket: `snapshot`, `game`, `deleted`, `review`, `engine`, `courses`, `course`, `course-deleted`, `course-progress`, `hello` |

## Architecture

```text
Browser (React 19 + Vite + Tailwind + react-chessboard + chess.js)
  │ REST mutations + WebSocket public state
  ▼
Express 5 process (127.0.0.1:3000)
  ├─ /mcp        MCP Streamable HTTP (official TypeScript SDK v2)
  ├─ /mcp/courses  Course-authoring MCP, disjoint tool list
  ├─ /api/*      REST for the human UI
  ├─ /ws         WebSocket live updates (server → client)
  └─ /           built React SPA
        │
        ├─ shared in-memory GameStore (chess.js rules, seats, tokens)
        ├─ CourseStore + ProgressStore (lessons, quizzes, learner progress)
        └─ ReviewService → Stockfish (UCI child process, auto-downloaded)
```

Key points:

- **One source of truth.** The website and every MCP agent mutate the same
  `GameStore`. An agent spawning a separate stdio server would not see the
  website's games, which is why HTTP MCP is the product's transport.
- **Courses are a parallel aggregate.** `CourseStore` and `ProgressStore` keep
  lessons, quizzes, and learner progress apart from live games. They are exposed
  to the browser over REST/WebSocket and to the authoring agent only through
  `/mcp/courses`; `/mcp` (game play) never sees those tools.
- **Official MCP SDK v2** (`@modelcontextprotocol/server`), Streamable HTTP,
  loopback-only with Host/Origin validation from `@modelcontextprotocol/express`.
- **Seat tokens** prevent one agent from moving for the other player.
- **Saved games.** Every mutation rewrites `<data-dir>/games/<game-id>.json`, and
  saved games are reloaded at startup. The store still caps at 200 in-memory
  games and evicts the oldest finished ones (their saved files are removed too).
- **Reviews are a separate artifact.** Analysis runs in one background job at a
  time, results are cached in memory and `<data-dir>/reviews/`, and progress is
  broadcast over the WebSocket. A saved review is reused after a restart.
- **No ratings, accounts, chat, or remote access.** The server is loopback-only;
  the external downloads are the Stockfish binary, the runtime piece themes, and
  the opening dataset, each pinned and verified (the opening TSVs by SHA-256).

### Source layout

```text
src/
  index.ts            CLI, HTTP server, engine/review wiring, static serving
  mcp.ts              MCP tool registration (including review_game)
  game.ts             chess.js wrapper: moves, status, draw/resign, PGN, ASCII board
  storage.ts          Game + review JSON persistence, directory resolution
  store.ts            GameStore: ids, seats, token hashes, events, limits, restore
  courseMcp.ts        Course-authoring MCP server (mounted at /mcp/courses)
  courses/            Course validation, JSON storage, in-memory CourseStore
  format.ts           Text formatting for MCP tool results and reviews
  server/app.ts       Express REST routes + MCP mount + error handling
  server/ws.ts        WebSocket server, Origin check, game/course/review broadcast
  engine/             Stockfish locate/download/verify, UCI client, lifecycle
  openings/           Opening dataset download/verify, book build, service
  review/             Move classification, accuracy, review queue/persistence
  shared/protocol.ts  Types shared by server and web
  shared/openings.ts  Position-keyed book lookup, shared by server and web
  shared/eval.ts      Win-probability/accuracy maths and eval formatting
web/src/              React app: lobby, game and course views, board, live store
scripts/              Maintenance checks (e.g. `pnpm openings:check`)
test/                 Rules, store, review, engine, MCP, REST/WebSocket tests
.oxlintrc.json        Strict Oxlint policy
.github/workflows/    CI: lint, typecheck, test, build
.vscode/              Recommended Oxc extension + lint-on-type settings
```

## Scripts

| Command | Behavior |
| --- | --- |
| `pnpm dev` | tsx watch + Vite middleware on port 3000 (HMR, no build) |
| `pnpm build` | Typecheck server and web, then build the SPA into `dist/web` |
| `pnpm start` | Run the built server and SPA |
| `pnpm lint` | Strict Oxlint; warnings and unused suppressions fail the run |
| `pnpm lint:fix` | Apply Oxlint's safe fixes |
| `pnpm typecheck` | Server, web, and test TypeScript checks |
| `pnpm test` | Vitest: rules, store, review/engine, MCP round-trip, REST + WebSocket |
| `pnpm test:watch` | Vitest in watch mode |
| `pnpm check` | lint + typecheck + tests |
| `pnpm validate` | check + production build |

## Linting

Linting is enforced with [Oxlint](https://oxc.rs/docs/guide/usage/linter/).
`.oxlintrc.json` is deliberately strict:

- All **correctness**, **suspicious**, and **performance** rules are errors.
- TypeScript, React, JSX accessibility, import, promise, node, Vitest, unicorn,
  and Oxc plugins are enabled.
- React recommended rules are explicit (`react/rules-of-hooks`,
  `react/button-has-type`, `react/jsx-no-target-blank`,
  `react/jsx-no-useless-fragment`, `react/no-unknown-property`) alongside
  Oxlint's native React Compiler and hooks rules (`react/purity`,
  `react/immutability`, `react/set-state-in-*`, `react/exhaustive-deps`).
- Tailwind CSS v4 is wired through Oxlint's `jsPlugins` support using
  `eslint-plugin-tailwindcss` with `settings.tailwindcss.cssConfigPath` pointing
  at `web/src/styles.css`. It enforces canonical Tailwind spellings, flags
  unnecessary arbitrary values, unknown class names, and contradicting classes.
- Selected additional rules are errors: `eqeqeq`, `prefer-const`, `no-var`,
  `typescript/no-explicit-any`, `typescript/no-non-null-assertion`,
  `typescript/consistent-type-imports`, `import/no-cycle`,
  `import/no-duplicates`, `unicorn/prefer-node-protocol`,
  `react/self-closing-comp`, and more.
- **Type-aware linting** is enabled through `oxlint-tsgolint` (`--type-aware`).
  It catches unsafe type assertions, unnecessary conversions/assertions, unbound
  methods, and misused spreads in the server, tests, and `.tsx` components.
- `console` is banned in the web app; server/test logging is explicitly allowed.
- Test fixtures relax only `no-non-null-assertion`, `no-unsafe-type-assertion`,
  and `no-unnecessary-type-parameters` because they intentionally decode JSON
  fixtures.
- The noisy `pedantic` and `style` categories (`sort-keys`, `one-var`,
  `jsx-max-depth`, `no-magic-numbers`, etc.) stay off by design; high-signal
  rules from those categories are enabled individually.
- `--deny-warnings` and `--report-unused-disable-directives` mean a warning or a
  stale suppression fails CI.

Install the recommended **Oxc** VS Code extension (`oxc.oxc-vscode`) from the
workspace recommendations; `.vscode/settings.json` enables lint-on-type and
applies safe fixes on request. Changes are checked by
`.github/workflows/ci.yml`.

## Validation

The repository ships with:

- Oxlint with type-aware rules: **0 warnings, 0 errors** across 99 files and
  296 rules.
- TypeScript: server, web, and test configs all clean.
- Rules tests: Fool's mate, castling, en passant, promotion, draws,
  resignation, illegal moves, PGN and ASCII output.
- Store tests: seat tokens, turn order, hotseat, events, lookup, deletion.
- Storage tests: per-platform save directories, save/reload round-trips (including
  seat tokens, draw offers, and finished games), review round-trips, corrupt-file
  tolerance, deletion.
- Review tests: UCI parsing, release selection, checksum/size rejection,
  win-probability bands, brilliant/great detection, mate scores, auto-start on
  game end, engine-unavailable failures, persistence and reuse.
- MCP tests: two in-process clients create/join/play, `wait_for_move` resolves
  on the opponent's move, errors are `isError`.
- API tests: real HTTP server + WebSocket broadcast + validation errors, engine
  and review routes when no engine is configured.
- Course tests: catalog build/round-trip, lesson and quiz validation, store
  persistence/tokens, step/quiz grading, progress persistence, REST attempts and
  quiz answers with live `course-progress` broadcasts, and disjoint `tools/list`
  results for `/mcp` vs `/mcp/courses`.
- **179/179 Vitest tests pass.**

The server was also smoke-tested over the wire with the official MCP client
(`tools/list`, `create_game`, `join_game`, UCI moves, `get_game`) and the UI was
checked in a headless browser, including a live WebSocket move update.

## Security and limitations

- Binds to `127.0.0.1` only; do not expose it publicly without adding auth and
  TLS. There is no remote access mode.
- Seat tokens are high-entropy and only their SHA-256 hashes are stored (in
  memory and in saved game files); public game state never includes them.
- Game deletion is available to anyone on the local machine.
- Saved games and reviews live in the current user's profile (see
  [Saved games](#saved-games)); the server does not encrypt them.
- The first run downloads the official Stockfish release (~80 MB) into the data
  directory, the runtime piece themes (a few MB) in parallel under
  `<data-dir>/themes/`, and the opening dataset (~410 KB) under
  `<data-dir>/openings/`. The engine URL, byte size, and SHA-256 digest are pinned
  in `src/engine/releases.ts`; each opening TSV is pinned the same way in
  `src/openings/release.ts`. Downloads are verified before use, and archive paths
  are checked for traversal. Use `--no-engine-download` to disable all three
  downloads, or `--engine <path>` to replace the engine download.
- Stockfish runs as a local child process. Only the configured path is executed;
  no part of an HTTP/MCP request can choose the binary.
- The MCP server has no resources or prompts; all state is returned by tools.

## License

Apache-2.0. See [LICENSE](./LICENSE).