
chess-mcp
io.github.T145/chess-mcp
Local chess web app and MCP server for humans vs LLMs and LLM vs LLM play.
Documentation
chess-mcp
A local chess web app and MCP server for humans vs LLMs and LLM vs LLM games.
- One command, no checkout:
npx -y @t145/chess-mcp --stdiostarts the web app and the MCP server in one process and opens the lobby in your browser. - Open a board in the browser, play moves, watch games update live.
- Create a local account with a username and password so your identity follows you across games.
- Invite any MCP-capable agent (Cline, Claude Code, etc.) into the other seat with one copy-paste prompt.
- Agents reach the same game state over Streamable HTTP (
/mcp) or stdio (--stdio); both transports share one store with the browser. - 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 remote account service.
Requirements
- Node.js 22+ (Node 24 recommended; required by
better-sqlite313). This is the only requirement for thenpxquick start below. - pnpm 11+ — only when running from a checkout.
Quick start
One command, no checkout
npx -y @t145/chess-mcp@1.0.0 --stdio
That single process starts the web app, serves the game MCP tools on
stdin/stdout, and opens the lobby at http://127.0.0.1:6464/. Logs go to
stderr so stdout stays a clean MCP channel, and --no-open keeps the browser
closed. Any stdio-capable host can use the same command as its server definition:
{
"mcpServers": {
"chess": {
"command": "npx",
"args": ["-y", "@t145/chess-mcp@1.0.0", "--stdio"]
}
}
}
Drop --stdio and the package is just the web app
(npx -y @t145/chess-mcp), with agents connecting over Streamable HTTP at
/mcp — see MCP client configuration.
@t145/chess-mcpis published from this repository; the release and registry steps are in the release section.
From a checkout
pnpm install
pnpm dev
Open http://127.0.0.1:6464.
For a production-style run:
pnpm build
pnpm start
pnpm start serves the built React app, the REST API, the WebSocket, the MCP
endpoints, and — with --stdio — stdin/stdout, all from one process.
How the pieces fit
One chess-mcp process owns every game. The React app in web/ talks to it over
REST and WebSocket, agents talk to the same store over /mcp (Streamable HTTP)
or stdin/stdout (--stdio), and everyone sees the same boards and moves. The
Architecture section has the full picture.
CLI options
chess-mcp [options]
--port <number> Port to listen on (default: 6464, 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
--stdio Also serve the game MCP tools on stdin/stdout (logs move to stderr)
--open Open the lobby in your browser on start (default with --stdio)
--no-open Never open a browser
--dev Serve the React app with Vite middleware (HMR, no build)
-h, --help Show help
The server always binds to 127.0.0.1. With --open — automatic under
--stdio — it opens the lobby in your default browser; otherwise open the
printed URL.
Saved games
Games are written after every change (create, join, move, draw, resign), so the
lobby is restored the next time the server starts. All application state lives
in one SQLite database at <data-dir>/chess-mcp.db:
gamesstores each game snapshot as a JSON document pluscreated_at/updated_at;reviewsstores review summaries, cascading when their game is deleted;accountsstores usernames, scrypt password parameters, and name/timestamps;sessionsstores SHA-256 session-token hashes with an expiry index;coursesstores validated course snapshots and status;course_progressstores per-learner step/quiz progress.
The database runs in WAL mode with foreign keys enabled. Downloaded assets live
beside it under 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 row (and its review). Accounts work the same way: only the
salted scrypt password hash is saved, and saved seats remember their profileId.
Accounts and sign-in
Accounts are local and password-protected. Create one from the lobby
(Sign in → Create account) or with the signup MCP tool.
- Passwords are salted and hashed with scrypt on the server. The password itself is never stored, logged, or sent back to the browser.
- A successful signup/signin creates a 30-day session. The browser receives it
as an
HttpOnlycookie (chess_mcp_session); only the session token hash is stored in thesessionstable, so sessions survive a server restart and a browser restart. - Games created or joined while signed in store the account id on the seat. The browser does not need a per-game seat token: the session cookie is accepted by move/draw/resign/swap, and the same account is recognized in every game it plays.
- Usernames are unique and case-insensitive (3–24 characters: lowercase
letters, digits,
.,_,-). Passwords must be at least 8 characters. - Signing out deletes the server session and clears the cookie. Renaming the display name changes future seats; seats already claimed keep the name they were created with.
MCP clients have no cookies, so signup/signin return a session token. Pass
it as profile_token to create_game/join_game, or directly as seat_token
in any game that account plays. The token is stored hashed and works until it
expires or signout ends it.
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
- Click New game.
- Sign in first if you want the game linked to your account; otherwise enter a guest name. Pick White (or Black) and choose a time control (or No clock).
- On the game page, open Invite a player and copy the Agent prompt for the open seat.
- Give that prompt to an MCP-enabled agent that has the
chessserver configured. - Play in the browser. The agent blocks on
wait_for_move, receives your move, and replies. - 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
{
"mcpServers": {
"chess": {
"type": "streamableHttp",
"url": "http://127.0.0.1:6464/mcp"
},
"chess-courses": {
"type": "streamableHttp",
"url": "http://127.0.0.1:6464/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.
One command: --stdio
Most hosts launch an MCP server as a child process and speak stdio to it. Adding
--stdio makes the same process serve the game MCP tools on stdin/stdout and
the web app on http://127.0.0.1:<port>, sharing one GameStore:
{
"mcpServers": {
"chess": {
"command": "npx",
"args": ["-y", "@t145/chess-mcp@1.0.0", "--stdio"]
}
}
}
In this mode every log line goes to stderr (stdout carries MCP frames), and
the lobby opens in your default browser as soon as the port is listening, so the
player never has to find the URL. --no-open (or CHESS_MCP_OPEN=0) suppresses
that; --open forces it for a normal --port run too.
The port must be free. Stdio mode owns the web app and the MCP tools in one
process, so a second process would mean a second copy of the state; start it with
--port <number> when 6464 is taken. The course-authoring server on
/mcp/courses stays HTTP-only.
Agent loop
Use the chess MCP server at http://127.0.0.1:6464/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="<your board check>")
Repeat until the game ends.
To keep one identity across several games, call signup once (or signin
later) and pass the returned session token as profile_token to every
create_game/join_game call, or directly as seat_token in any game that
account plays. The server keeps the session until it expires or signout ends it.
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}:
1. e4 {FEN rnbqkbnr/...; e4 is defended by nothing but no black piece attacks it yet; opens
d1-h5 and f1-b5} e5 2. Nf3 {develops, covers d4/e5}
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 check down before moving is the cheap part: it forces the FEN, the defenders and the lines the move opens into the sentence, which is exactly where hasty moves go wrong. Quote the FEN you are moving from, name the defender behind every "this is safe" claim, and when the move is a capture or a pawn move, name the squares it vacates plus any enemy slider that now sees through them. A note written from the board rather than from the previous plan is the point — if you cannot fill those in, re-read the board before moving. 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:
Use the chess course MCP server at http://127.0.0.1:6464/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 stored in the SQLite courses table as validated JSON snapshots 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
- Open Classroom in the retractable sidebar and click New course (or use the sidebar's New menu).
- 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.
- 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. - Give the prompt to an agent configured with
chess-courses. Itsadd_lessonandadd_quizcalls appear live on the page through the WebSocket; no reload. - 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
lessonIdappear 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_lessonand course history withset_course_history.
Progress is stored per learner in the SQLite course_progress table.
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:
--engine <path>orCHESS_MCP_ENGINE;stockfishonPATH;- common install folders (
/usr/games,/usr/bin,/usr/local/bin,/opt/homebrew/bin,%LOCALAPPDATA%\Stockfish,Program Files\Stockfish); - 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
(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).
| Tool | Purpose |
|---|---|
signup | Create an account (username, password, optional name). Returns a profile id and a session token. |
signin | Sign in with username/password and return a session token. |
signout | End a session token. |
get_profile | Read a profile by profile_id or session token, with every game where it holds a seat. |
create_game | Create a game and claim white, black, or no seat (none), with an optional time_control preset and optional session profile_token. Returns a game id and seat token. |
join_game | Claim an open seat, optionally as an account via profile_token. 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 board check 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:
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)
Mutating game routes accept the account session cookie in place of token.
Guest games still use the per-game seat token returned by create/join.
| 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 |
GET /api/auth/session | Current signed-in profile, or { profile: null } |
POST /api/auth/signup | Create an account { username, password, name? }; sets the session cookie |
POST /api/auth/signin | Sign in { username, password }; sets the session cookie |
POST /api/auth/signout | Delete the session and clear the cookie |
GET /api/profiles/:id | Profile plus the games where it holds a seat |
PATCH /api/profiles/:id | Rename your display name { name } (requires the session cookie) |
POST /api/games | Create a game (name, color: white, black, random, or none; optional timeControl). A signed-in account is linked automatically. |
GET /api/games/:id | Public game state |
POST /api/games/:id/join | Claim { name, seat }; a signed-in account is linked automatically |
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
MCP host (stdio) Browser
stdin/stdout ⇄ JSON-RPC REST mutations + WebSocket state
│ │
▼ ▼
┌────────────────────────────────────────────────────────────┐
│ chess-mcp process — Express 5 on 127.0.0.1:6464 │
│ │
│ /mcp MCP Streamable HTTP (official SDK v2) │
│ /mcp/courses Course authoring MCP (disjoint tools) │
│ /api/* REST for the human UI │
│ /ws WebSocket live updates (server → client) │
│ / built React SPA │
│ --stdio the same game tools on stdin/stdout │
└───────────────────────────────┬────────────────────────────┘
│
┌──────────────────────────┼──────────────────────────┐
▼ ▼ ▼
GameStore CourseStore + ReviewService
chess.js rules, seats, ProgressStore → Stockfish
token hashes, events lessons/quizzes/progress (UCI child process)
│
▼
SQLite: <data-dir>/chess-mcp.db (WAL, foreign keys)
Key points:
- Two entrances, one store. The browser,
/mcpclients, and a--stdioclient all mutate the sameGameStorein one process. A separate stdio server would own a second copy of the state, which is why--stdioserves the tools from the process that already hosts the web app instead of bridging to another one. - The browser is part of the interface.
--stdiostarts the app and hands the lobby URL to the default browser (cmd /c starton Windows,openon macOS,xdg-openelsewhere); a headless host only sees the failure logged and keeps serving MCP. - Courses are a parallel aggregate.
CourseStoreandProgressStorekeep 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. - One tool implementation, two transports.
createMcpServerregisters the game tools once;createMcpHandlerexposes them over Streamable HTTP (loopback-only, with Host/Origin validation from@modelcontextprotocol/express) andserveStdioexposes the same factory on stdin/stdout. Both run on the official SDK v2 (@modelcontextprotocol/server). - Seat tokens prevent one agent from moving for the other player. An account session token can replace a seat token in every game the account plays, and the browser uses an HttpOnly session cookie.
- Accounts are local identities.
ProfileStorekeeps usernames, scrypt password hashes, and hashed session tokens in the SQLiteaccountsandsessionstables; games store only the profile id on a seat. - SQLite persistence. Every mutation writes to
<data-dir>/chess-mcp.dbthroughbetter-sqlite3; WAL mode and transactions replace per-entity JSON files. Game and course aggregates remain JSON documents inside their tables. Saved games are reloaded at startup. The store still caps at 200 in-memory games and evicts the oldest finished ones (their rows are removed too). - Reviews are a separate artifact. Analysis runs in one background job at a
time, results are cached in memory and the
reviewstable, and progress is broadcast over the WebSocket. A saved review is reused after a restart. - Version parity.
src/version.tsfeedsserverInfo.version;pnpm registry:version <semver>rewrites it together withpackage.jsonandserver.json, so the MCP handshake, the npm tarball, and the registry record never disagree. - Distribution is metadata plus CI.
server.jsoncarries two npm package entries (stdio and streamable-http) for the official MCP Registry, and.github/workflows/publish-mcp.ymlpublishes the package with npm trusted publishing (OIDC, no stored token) plus the metadata withmcp-publisher.github.com/mcpis curated by GitHub separately, so it needs a request after the registry record exists. - No ratings, chat, or remote access. Accounts are local username/password identities, not a hosted service. 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
src/
index.ts CLI, HTTP server, engine/review wiring, static serving
mcp.ts MCP tool registration (including review_game)
stdio.ts Same game tools over stdin/stdout for npx-style clients
version.ts Package version constant reported as the MCP server info
openBrowser.ts Platform launcher for the lobby URL
game.ts chess.js wrapper: moves, status, draw/resign, PGN, ASCII board
database.ts SQLite connection, pragmas, schema migrations
storage.ts Game + review SQLite repository, directory resolution
store.ts GameStore: ids, seats, token hashes, events, limits, restore
profiles/ Local accounts: scrypt password hashes, sessions, identity lookup
courseMcp.ts Course-authoring MCP server (mounted at /mcp/courses)
courses/ Course validation, SQLite repositories, 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 (openings, review relabel) + version sync
test/ Rules, store, review, engine, MCP/stdio, browser launcher, REST/WebSocket
server.json MCP Registry metadata: stdio + streamable-http package entries
.oxlintrc.json Strict Oxlint policy
.github/workflows/ CI (lint, typecheck, test, build) and registry publishing
.vscode/ Recommended Oxc extension + lint-on-type settings
Scripts
| Command | Behavior |
|---|---|
pnpm dev | tsx watch + Vite middleware on port 6464 (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 + stdio round-trip, REST + WebSocket |
pnpm test:watch | Vitest in watch mode |
pnpm check | lint + typecheck + tests |
pnpm validate | check + production build |
pnpm registry:version <semver> | Sync the version in package.json, server.json, and src/version.ts |
Linting
Linting is enforced with Oxlint.
.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
jsPluginssupport usingeslint-plugin-tailwindcsswithsettings.tailwindcss.cssConfigPathpointing atweb/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.tsxcomponents. consoleis banned in the web app; server/test logging is explicitly allowed.- Test fixtures relax only
no-non-null-assertion,no-unsafe-type-assertion, andno-unnecessary-type-parametersbecause they intentionally decode JSON fixtures. - The noisy
pedanticandstylecategories (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-warningsand--report-unused-disable-directivesmean 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 116 files and 409 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.
- Account tests: signup/duplicate-username/password rules, scrypt hashes in SQLite, sign-in and bad credentials, session persistence across restarts, one session across multiple games, profile ids in saved seats, and refusing to occupy both sides with one account.
- Storage tests: per-platform save directories, SQLite save/reload round-trips (including seat tokens, draw offers, and finished games), review round-trips, corrupt-row 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 sign up/sign in, create/join/play,
wait_for_moveresolves on the opponent's move, sessions work across games, and errors areisError. - Stdio test: an
InMemoryTransportclient lists and calls the game tools, and the game it creates is visible in the sameGameStorethe web app serves. - Browser test: Windows/macOS/Linux launcher commands, plus the detached launch call, without opening a window.
- API tests: real HTTP server + WebSocket broadcast + validation errors, account signup/signin/signout cookies, session-authenticated moves, 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-progressbroadcasts, and disjointtools/listresults for/mcpvs/mcp/courses. - 192/192 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.1only; 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 the SQLite game snapshots); public game state never includes them.
- Account passwords are salted and hashed with scrypt; session tokens are stored
only as SHA-256 hashes and delivered in an
HttpOnly,SameSite=Laxcookie. The SQLite database in the local data directory is not encrypted. - Game deletion is available to anyone on the local machine.
- Saved games, reviews, accounts, and progress live in the current user's data directory (see 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 insrc/engine/releases.ts; each opening TSV is pinned the same way insrc/openings/release.ts. Downloads are verified before use, and archive paths are checked for traversal. Use--no-engine-downloadto 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.
Publishing to the MCP Registry (github.com/mcp)
https://github.com/mcp is GitHub's curated registry, served by
https://api.mcp.github.com/v0.1/servers. Publishing to it is a two-part flow,
and the second part is manual:
- publish the package to npm and the server metadata to the official open
registry at
registry.modelcontextprotocol.io; - ask GitHub to include it in
https://github.com/mcp(emailpartnerships@github.comwith the server name and repository, as described in GitHub's registry walkthrough).
The open registry is the self-serve half. GitHub pulls from it, but its own
listing is curated, so a record in registry.modelcontextprotocol.io is
necessary, not sufficient, for an entry at github.com/mcp.
What the repository already ships
| File | Purpose |
|---|---|
server.json | Registry metadata: name io.github.T145/chess-mcp plus two npm package entries — stdio (--stdio) and streamable-http (--port) |
package.json → mcpName | Ownership proof, must equal the server.json name exactly |
package.json → repository | Ties the record to https://github.com/T145/chess-mcp for the GitHub card |
scripts/set-version.ts | Keeps package.json, server.json, and src/version.ts on the release tag's version (pnpm registry:version <semver>) |
.github/workflows/publish-mcp.yml | Tag-driven publish of the npm package and the registry record |
.github/workflows/publish-registry.yml | Metadata-only registry publish (workflow_dispatch), no npm release |
Installed from a registry, the stdio entry is the zero-setup path: the host
runs npx -y @t145/chess-mcp --stdio, npm fetches the package, the web app and
the MCP tools start in one process, and the lobby opens in the default browser.
The only prerequisite is Node.js 22+ on the user's machine; the first launch also
downloads Stockfish (~80 MB), the piece themes, and the opening book into the
data directory unless CHESS_MCP_NO_ENGINE_DOWNLOAD=1 is set. Headless hosts can
set CHESS_MCP_OPEN=0 to keep the browser closed.
Two rules drive the naming:
server.json.namemust beio.github.<github-login>/<server>. The registry keeps the login's canonical casing (for exampleio.github.ChromeDevTools/...), hereio.github.T145/chess-mcp.- the npm package must be public and carry a matching
mcpName. Unscopedchess-mcpis already taken on npm, so the package is scoped to@t145. If your npm account is nott145, changenameinpackage.jsonand everypackages[].identifierinserver.jsontogether;mcpNamestays the registry name.
Publish once by hand (bootstrap)
Trusted publishing is configured on a package that already exists, so the very first version (1.0.0 here) is published from your machine; the first CI release after that is a new version, for example 1.0.1:
npm refuses to create or publish a package unless the account has two-factor authentication enabled, or the publish uses a granular access token with bypass 2FA enabled. Enable 2FA once at npmjs.com → Account → Two-factor authentication (auth-and-writes), then
npm publishprompts for the second factor. Without it the registry answers403 … Two-factor authentication or granular access token with bypass 2fa enabled is required, which npm's terser error output can show as a bare404.
# 1. Build and publish the package (prepublishOnly runs the build again)
pnpm run validate
npm login # web login; 2FA is required to publish
npm publish --access public # prompts for the 6-digit OTP, or pass --otp=<code>
# 2. Publish the registry metadata
# Windows: download the archive from
# https://github.com/modelcontextprotocol/registry/releases (mcp-publisher_windows_amd64.tar.gz)
# then: tar xzf mcp-publisher_windows_amd64.tar.gz
./mcp-publisher validate # schema check against the registry
./mcp-publisher login github # device-code OAuth
./mcp-publisher publish # reads server.json in the current directory
Use npm publish for this first publish: pnpm publish can miss the OTP prompt
and surface the registry's 403 ("two-factor authentication … is required") or a
bare 404 instead. The non-interactive equivalent is
npm publish --access public --otp=<current 6-digit code>.
Verify the record:
curl "https://registry.modelcontextprotocol.io/v0.1/servers?search=io.github.T145/chess-mcp"
Once it is there, email partnerships@github.com to request the GitHub registry
listing, and include the npm package name and repository URL.
Trusted publishing (no NPM_TOKEN)
npm recommends OIDC trusted publishing for CI releases: the workflow exchanges
GitHub's short-lived identity token for a registry token, so there is no
long-lived secret to leak or rotate. pnpm implements the same exchange, so
pnpm publish works unchanged.
- Open npmjs.com → Packages →
@t145/chess-mcp→ Settings → Trusted publishing → Add trusted publisher → GitHub Actions. - Fill in:
- Organization or user:
T145 - Repository:
chess-mcp - Workflow filename:
publish-mcp.yml(filename only, must match) - Environment name: leave empty unless you add the same
environment:to the job in the workflow - Allowed actions: also allow
npm publish. Configurations created after 3 Sep 2026 default to staged publishing only, and this project publishes directly.
- Organization or user:
- Make the next CI publish happen within 2 days; an unvalidated configuration expires and must be recreated.
- After the first successful OIDC release, harden the package under Settings → Publishing access → Require two-factor authentication and disallow tokens.
The workflow already has the two requirements: permissions: id-token: write,
and no NODE_AUTH_TOKEN. Keep pnpm at 11.1.3+ (this repo pins 11.22.0),
because older versions sent the literal ${NODE_AUTH_TOKEN} placeholder that
actions/setup-node writes into .npmrc. On a public repository publishing a
public package, provenance attestations are attached automatically — no
--provenance flag is needed.
Publish on every release tag
The workflow does all of the above:
git tag v1.0.1
git push origin v1.0.1
It runs pnpm run validate, syncs the version in package.json, server.json,
and src/version.ts from the tag, publishes
with npm trusted publishing, verifies the pinned mcp-publisher release with
cosign, authenticates to the registry with GitHub OIDC, and publishes
server.json. A published version is immutable, so a corrected server.json
needs a new version.
The registry verifies ownership by fetching that exact version from npm, so a
fresh release can return "version was not found" for a moment; the workflow
retries that case five times. To re-publish metadata without cutting a package
release — for example after a transient failure — run the Publish MCP Registry
metadata workflow (workflow_dispatch). It performs the same cosign check and
OIDC login and skips npm entirely.
Transport caveat
chess-mcp is natively a Streamable HTTP server, so the registry record carries
both shapes and lets the host choose:
- the stdio entry runs
npx -y @t145/chess-mcp --stdio, which starts the web app and the MCP tools in one process. This is the form every host supports; - the streamable-http entry describes the npm package with
transport.type: "streamable-http"and the URLhttp://127.0.0.1:{--port}/mcp(the{--port}token resolves from the--portpackage argument). Only hosts that can launch a process and then connect to its URL use it; others try to speak stdio to a process that is waiting on HTTP.
For a host that does neither, start the server yourself
(npx @t145/chess-mcp --port 6464) and copy the URL configuration from
MCP client configuration. The course-authoring
server on /mcp/courses is not in server.json; add it by hand when an agent
needs it.
License
Apache-2.0. See LICENSE.
@t145/chess-mcpnpm install @t145/chess-mcp@t145/chess-mcpnpm install @t145/chess-mcp