convez.ai
MCP ServerIntegração & APIsIntermediário
Azeajr

Chess MCP – Análise de Xadrez com Stockfish

Azeajr/chess-mcp

Engine Stockfish via MCP para análise de xadrez sem alucinações em IA

Ver no GitHub
InicialPluginScore · de 0 a 100

Servidor MCP que integra o engine Stockfish para análise de xadrez precisa em agentes IA como Claude Code. Inclui 32 ferramentas para validação de posições, construção de repertório e revisão de partidas, mais uma PWA SolidJS para estudo offline. Elimina movimentos alucinados ao grounding em análise real do engine.

Instalação

$npx convez-ai Azeajr/chess-mcp

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
1
Forks
1
Acompanhando
0
Saúde
42%
Último commit
há 2 semanas
Versão
v1.1.21
Issues abertas
0
Contribuidores
1

Casos de uso

  • Análise automática de partidas de xadrez com validação de movimentos legais
  • Construção e estudo de repertório com gap analysis e avaliação em tempo real
  • Integração de chess analysis em fluxos de trabalho com Claude Code

Veredito

Implementação robusta que resolve o problema real de alucinações em análise de xadrez via grounding em engine legítimo. TypeScript/Node.js clean, PWA offline-first e arquitetura bem modularizada. Nicho específico mas bem executado para jogadores sérios e desenvolvedores de AI.

README

A tradução para o português deste README ainda está na fila.

chess-mcp

CI

Grounded chess analysis for AI agents (Claude Code, etc.) via Stockfish — plus a local repertoire-building PWA. The MCP server runs as a single Node.js process (no Docker, no Python); a SolidJS web app shares the same TypeScript chess logic. Eliminates hallucinated moves and illegal lines by letting the agent validate positions and query the engine directly.

Note: The MCP server is a Node.js/TypeScript implementation (apps/mcp-server, all 32 tools). .mcp.json launches it directly — no container, no port, no host Stockfish install (the engine ships as a bundled wasm).

Quickstart

Prerequisites: Node.js ≥ 20 + pnpm + Claude Code (claude).

git clone https://github.com/Azeajr/chess-mcp
cd chess-mcp
pnpm install
claude   # approve the `chess-analysis` server when prompted (one-time)

.mcp.json registers one stdio server, chess-analysis, launched as node --import tsx apps/mcp-server/src/index.ts — Stockfish (the stockfish npm wasm), chessops, and the ECO/structure data all bundled. The former chess-files proxy is gone: its file-path tools (load_repertoire_from_file / export_repertoire_to_file) are part of the one server now. Skills in .claude/skills/ load automatically: /chess-game-review, /repertoire-builder, /analyze-position, /annotate-pgn.

Web app (repertoire builder PWA)

pnpm dev          # http://localhost:5173  (pnpm dev:host to expose on your LAN)
pnpm --filter @chess-mcp/ui build   # production PWA (installable, offline)

A SolidJS board UI for building/studying repertoires: play moves into a variation tree, engine-eval arrows colored by repertoire congruence, on-demand gap scan, Lichess cloud eval, and an in-app chat (OpenRouter — set your key + model in Settings). Working repertoire autosaves to IndexedDB; open/save PGN via the File System Access API.

In-app chat tools (client-side). The chat's tools run entirely in the browser against the shared chess-tools logic + the local Stockfish wasm — the same repertoire toolset the MCP server exposes (find_repertoire_gaps, get_structural_profile, analyze_repertoire_congruence, suggest_*, game review, gaps, …), reimplemented with no backend. So the chat is fully featured in pnpm dev and in the deployed/built PWA (e.g. on a static host like Cloudflare Pages — no Node process required). The engine-dependent orchestration is the shared implementation the Node server uses too (packages/chess-tools/src/enginetools.ts), so server and PWA stay in lockstep. Only the host-filesystem tools (*_from_file/*_to_file) are MCP-only — the PWA uses the File System Access picker instead.

A workflow mode selector in the chat panel (General / Repertoire / Game review / Position / Annotate) injects the matching playbook into the system prompt — the PWA counterpart of the Claude Code skills (apps/ui/src/llm/workflows.ts), telling the assistant which tools to call in what order plus the grounding rules. The skills under .claude/skills/ remain the Claude Code version (handle-based); the PWA prompts are adapted to its handle-free, current-tree tools.

Problem

AI agents reviewing chess games generate moves from pattern-matching, not board state. They have no legal move generator and no engine — so they invent plausible-looking but illegal or nonsensical lines. This MCP fixes that by giving the agent real tools to check its work before stating anything.

Architecture

pnpm monorepo, one shared chess library serving both the MCP server and the web app:

packages/chess-tools   shared TypeScript logic (chessops + structure classifier + ECO +
                       congruence + gaps + game review + rate-limited HTTP)
apps/mcp-server        Node MCP server — 32 tools over chess-tools + stockfish (npm wasm)
apps/ui                SolidJS PWA — board, congruence arrows, gaps, cloud eval, chat

Claude Code ──(stdio)──► apps/mcp-server   (node --import tsx; no Docker, no port)

Tools

Game analysis

ToolInputOutput
get_game_summaryPGN, depthCounts, accuracy %, worst 3 moves, opening — call this first
analyze_gamePGN, depth, min_cp_loss, verboseMistake list (cp_loss ≥ min_cp_loss): move, cp_loss, classification, best_move. verbose=true adds eval_after + best_pv
get_positionPGN, move_number, color, depthOne move's detail: FEN, eval, best_move, best_pv, alternatives — drill-down from summary/analyze
evaluate_positionFEN, depth, multipvCentipawn score, best move, top line; multipv>1 adds ranked candidates (top-N moves)
compare_movesFEN, moves[], depthRanks YOUR candidate moves (best→worst): each move, eval, cp_loss vs best, pv; unrecognized inputs returned in illegal. Scores the exact moves you pass — even ones the engine wouldn't pick
validate_lineFEN, moves[]Valid bool, which move fails and why
get_legal_movesFEN, uciLegal moves as a SAN string; uci=true for a UCI+SAN list
validate_fenFENValid bool + normalized FEN, side to move, game-over flag; rejects illegal-but-parseable positions. Run on a user-supplied FEN before analysis
validate_pgnPGNValid bool + mainline ply count, has-variations flag, headers. Run on a user-supplied PGN before analysis
identify_openingPGNECO code + opening name (deepest named position); 3700-opening table
export_annotated_pgnPGN, depth, min_cp_lossAnnotated PGN string: NAG glyphs (?!/?/??) + eval & best-move comments on flagged moves, mainline and variations, plus moves_annotated count

Repertoire analysis

ToolInputOutput
load_repertoirePGN (variation tree), colorHandle (repertoire_id) + tree stats — call this first; avoids re-sending the full PGN on every call
get_structural_profilerepertoire_id, variation_path?Single-node: pawn structure class, confidence, primitives, theme tags, open files. variation_path=null → aggregate fingerprint (structures + theme rollup) over all leaves
analyze_repertoire_congruencerepertoire_id, min_severity, limitFlags thematic inconsistencies, judged WITHIN each opening system (lines clustered by move-order-robust system, not first move): structure outliers, weakness mismatches, center-handling splits — each with its cluster label + drill-down path; plus a clusters partition
find_repertoire_gapsrepertoire_id, depth, min_severity, limit, max_positionsEngine scan for completeness: at every opponent-to-move node you already answer, flags strong opponent replies the tree doesn't cover, each with drill-down path + severity
get_repertoire_coveragerepertoire_id, limitEngine-free tree hygiene: dangling lines (a leaf where it's your move = no prepared reply) vs natural frontiers, plus depth hints
suggest_complementary_linesrepertoire_id, FEN, mode, depth, limitContinuations from an anchor FEN: low_memorization ranks by structural overlap with the existing repertoire; sharp maximizes imbalance
get_transpositionsrepertoire_id, limitPositions reached by more than one move order, with the converging SAN paths — study one, cover several
modify_repertoire_linerepertoire_id, path, action (prune/add/reorder), add_moves?, promote_move?Action — edit one line and get a NEW repertoire_id (clone-on-write; the source id is unchanged, so you branch/compare). Drives the single-session edit loop: every read tool works on the new id immediately
export_repertoirerepertoire_idThe edit loop's escape hatch — serialize the current tree back to a PGN string (one [Event]) for you to Write to disk; round-trips through load_repertoire

Structural analysis recognizes 19 canonical pawn structures — IQP, Carlsbad, Maroczy, French, Stonewall, King's Indian, Benoni, Closed Sicilian, Hanging pawns, Caro-Kann, Slav, Grünfeld Centre, Nimzo-Grünfeld, Hedgehog, Najdorf, Scheveningen, Symmetric Benoni, Lopez, and Benko — each gated on a core skeleton with graduated confidence (a position missing a peripheral pawn still classifies), the open-Sicilian family scored bidirectionally (reversed-English positions included), else unknown. The canon is traced to Flores Rios Chess Structures and Soltis Pawn Structure Chess; every scorer is validated against an engine-verified canonical FEN (see STRUCTURE_CLASSIFIER_DESIGN.md). Beyond the named class, every position also carries always-on theme tags (fianchetto, space, wing-majority, minority-attack, flank-vs-centre, colour-complex) — these stay informative even when the class is unknown (e.g. fianchetto systems), and the aggregate profile rolls them up across all leaves. Opening names come from the lichess-org/chess-openings dataset (CC0).

Every engine-backed tool (analyze_game, get_game_summary, get_position, evaluate_position, compare_moves, suggest_complementary_lines, find_repertoire_gaps, export_annotated_pgn) also accepts an optional time_limit (seconds): when set, the engine searches by wall-clock instead of depth — useful on slow hardware or for fast iteration. Depth stays the default and the reproducible path.

Closed error-code set: bad input returns one of invalid_pgn, invalid_fen, invalid_color, move_not_found, pgn_too_large, too_many_moves, repertoire_not_found, variation_not_found, invalid_mode, invalid_line (an illegal SAN in a supplied line, e.g. modify_repertoire_line add_moves), invalid_edit (a malformed tree-edit request). compare_moves echoes unrecognized/illegal moves in an illegal list rather than erroring.

Repertoire file I/O

Load a repertoire (and write an export) by file path, so a large PGN is read off disk and never piped through the model's context: no client-side truncation, no per-load token cost. In the Node server these are ordinary tools (the host-side chess-files proxy the Python deployment needed is gone — the one stdio process has the host filesystem directly).

ToolInputOutput
load_repertoire_from_filepath, colorReads the PGN file on the host in full, loads it, returns the same handle as load_repertoire (repertoire_id + tree stats) — the PGN never enters the model's context
export_repertoire_to_filerepertoire_id, pathSerializes the tree to a host PGN file, returns {path, bytes, leaves} only (never the PGN text)

Paths are confined to REPERTOIRE_DIR (default the repo's repertoires/). Errors: file_not_found / not_a_file / path_not_allowed / pgn_too_large / decode_error (host-side), invalid_pgn / repertoire_not_found (relayed), backend_unreachable. Registered in .mcp.json and opencode.json.

Recommended workflow

Game review:

  1. Call get_game_summary — small output, gives counts and worst moves.
  2. Call analyze_game — filtered to moves at or above min_cp_loss (default 50).
  3. Call get_position(pgn, move_number, color) to drill into a specific move. Returns that position's FEN for evaluate_position / validate_line / get_legal_moves.

Repertoire analysis:

  1. Call load_repertoire(pgn, color) — parse once, get back repertoire_id.
  2. Call get_structural_profile(repertoire_id) (no path) — aggregate structural fingerprint.
  3. Call analyze_repertoire_congruence(repertoire_id) — inconsistency list clustered by opening system; each item carries a paths array for drill-down.
  4. Call get_structural_profile(repertoire_id, variation_path) to inspect a specific flagged line.
  5. Call suggest_complementary_lines(repertoire_id, fen, mode) to extend or diversify from any position.

Single-session edit loop (no re-download, no new session): from any repertoire_id, call modify_repertoire_line(repertoire_id, path, action, …) to prune/add/reorder a line — it returns a NEW repertoire_id for the modified tree (the source id still resolves to the original, so you can branch and compare). Re-run the read tools above on the new id, iterate, then export_repertoire(final_id) and write the returned pgn to disk. The agent passes only paths + SAN the MCP surfaced — it never authors chess content.

Move classifications

LabelCP loss
good< 50
inaccuracy50–100
mistake100–200
blunder> 200

Scores are from white's perspective. Mate scores map to ±10000 cp.

Skills (Claude Code)

.claude/skills/ ships workflow skills that drive these tools — they load automatically in Claude Code and keep every move/line engine-grounded:

SkillUse
chess-game-reviewreview a game (PGN): verdict, key mistakes, validated lines
repertoire-builderanalyze a repertoire tree by color: structural themes, thematic congruence, soundness, gaps, extensions
analyze-positionsingle-FEN deep dive (puzzles, "best move here?")
annotate-pgnemit an annotated PGN artifact (?!/?/?? + comments)

Validate plugin / marketplace

claude plugin validate ./plugin   # validate plugin manifest + skills
claude plugin validate .          # validate marketplace catalog

OpenCode

opencode.json registers chess-analysis (the same stdio Node server as .mcp.json) automatically when running from the repo — approve the prompt, no manual setup needed. Skills in .claude/skills/ auto-discover. Just run opencode from the repo.

Configuration

The Node server runs as a local stdio process — no port, no transport setting, no STOCKFISH_PATH (the stockfish wasm is bundled). Environment variables it reads:

VariableDefaultDescription
REPERTOIRE_DIRrepo repertoires/Base dir that load_repertoire_from_file / export_repertoire_to_file paths are confined to
MAX_REPERTOIRES16Max cached repertoires (LRU eviction beyond this)
REPERTOIRE_TTL_S3600Idle seconds before a cached repertoire expires

Search depth (default 18, clamped 1–30), the per-call time_limit ceiling, find_repertoire_gaps budget, and the input caps (PGN/repertoire bytes, line length, multipv) are compiled-in constants.

Trust boundary. The server runs Stockfish on caller-supplied PGN/FEN. The input caps and the depth clamp (1–30) bound per-call work, and the repertoire handle cache is bounded (MAX_REPERTOIRES LRU + REPERTOIRE_TTL_S expiry) so loaded repertoires can't grow memory without limit. As a local stdio process it exposes no network surface.

Project layout

chess-mcp/
├── .mcp.json                # Claude Code MCP config: chess-analysis (stdio Node server)
├── opencode.json            # OpenCode MCP config: chess-analysis (stdio Node server)
├── .github/workflows/       # ci.yml — build, typecheck, smoke; tag-gated GitHub release
├── .claude/skills/          # standalone skills (auto-load when running claude in-repo, no namespace prefix)
├── .claude-plugin/
│   └── marketplace.json     # Claude Code plugin marketplace catalog (plugin install path)
├── plugin/                  # distributable Claude Code plugin
│   ├── .claude-plugin/
│   │   └── plugin.json      # plugin manifest: stdio Node MCP server + skills
│   └── skills/              # plugin skills (namespaced /chess-mcp:<skill> after install)
├── packages/
│   └── chess-tools/         # shared TS lib: GameTree, structure classifier, congruence, gaps, ECO, HTTP
├── apps/
│   ├── mcp-server/          # Node MCP server (@modelcontextprotocol/sdk, stdio) — 32 tools + stockfish wasm
│   └── ui/                  # SolidJS + Vite PWA: board, congruence arrows, gap scan, cloud eval, chat
├── scripts/                 # engine-free smoke: smoke-gametree.mjs, structure-accuracy.mjs
├── docs/design/             # design specs (repertoire, structure classifier, node migration, …)
├── sample-game.pgn          # anonymized single-game fixture
├── sample-repertoire.pgn    # sample White 1.d4 repertoire tree
└── ENGINEERING_PASSES.md    # reusable refactor/security/testing execution-loop prompts

Dependencies

Roadmap

Forward-looking plan (distribution, engineering, and feature backlog) lives in ROADMAP.md. Shipped to date:

  • Repertoire handle — load_repertoire(pgn, color) → repertoire_id avoids re-sending large variation-tree PGNs. Implemented with bounded LRU + TTL cache (default 16 entries / 1h idle expiry; overridable via env).
  • Opening names (ECO) — identify_opening(pgn) names the opening from a 3700-entry table vendored from lichess-org/chess-openings; get_structural_profile nodes carry the opening too.
  • classify_structure expansion — now 19 source-traced structures (added Hanging pawns, Caro-Kann, Slav, Grünfeld Centre, Nimzo-Grünfeld, Hedgehog, Najdorf, Scheveningen, Symmetric Benoni, Lopez, Benko) with graduated core+bonus confidence and bidirectional open-Sicilian scoring, plus always-on theme tags (A) rolled up in the aggregate profile. Each scorer is validated against an engine-verified canonical FEN; see STRUCTURE_CLASSIFIER_DESIGN.md.
  • time_limit param — every engine tool takes an optional time_limit (seconds) → Limit(time=N) instead of depth; clamped to [0.01, MAX_ENGINE_TIME_S]. Depth stays the reproducible default.
  • Variation-aware game analysis — the cached engine pass now walks the whole game tree (mainline + variations) once, keyed by SAN path. The mainline game tools project the mainline unchanged; side lines are analyzed in the same pass.
  • export_annotated_pgn tool — emits an engine-annotated PGN artifact (NAG glyphs + eval/best-move comments on flagged moves, across mainline and variations); the grounded, importable counterpart to the annotate-pgn skill.
  • More pawn structures — added Closed Sicilian (8th); French Advance was already covered by the French pattern. Further structures follow the same scripts/structure-accuracy.mjs harness-validated pattern (candidates: French Exchange, Hedgehog).
  • Repertoire completeness + move comparison — find_repertoire_gaps (engine scan for strong uncovered opponent replies), get_repertoire_coverage (engine-free dangling-line / tree-shape hygiene), and compare_moves (rank your own candidate moves from a FEN). 16 tools; closed error set unchanged.
  • Single-session edit loop — modify_repertoire_line (clone-on-write prune/add/reorder → new repertoire_id; source id unchanged, so branch/compare) + export_repertoire (tree → PGN string for the agent to Write). Load → mutate → re-analyze the new id → … → export, all in one session, no re-download. New error codes invalid_line, invalid_edit. See REPERTOIRE_DESIGN.md §9.
  • Thematic-cluster congruence — analyze_repertoire_congruence now clusters lines by move-order-robust opening SYSTEM (not the opponent's first move), so a system reached via several first moves is judged as one and distinct systems under one first move stay separate. Surfaces per-system inconsistencies a Black repertoire previously washed out. See REPERTOIRE_DESIGN.md §10.

License

MIT © 2026 Antonio Zea.

Ver o original no GitHub

Bom para

Relacionados