llm-chess-mcp
llm-chess-mcp
Un runtime de ajedrez MCP que permite a los LLM jugar, analizar y ajustar su fuerza sin externalizar cada decisión a un motor.
En lugar de devolver una única jugada, expone la fuerza objetiva (Stockfish), la probabilidad de jugada humana (Maia3) y las estadísticas de partidas reales (Lichess) para que el LLM elija cómo quiere jugar. El LLM se encarga de la estrategia y el juicio; el servidor MCP hace todo el cálculo.
Motores
Motor | Rol | Runtime |
Stockfish 18 (WASM) | Evaluación objetiva, mejores jugadas, multipv | En proceso ( |
Maia3 5M (ONNX) | Probabilidades de jugada humanas condicionadas al Elo | En proceso ( |
Lichess explorer | Estadísticas reales de partidas humanas | HTTP (requiere token) |
Todo se ejecuta dentro del proceso de Node: nada de motor externo ni runtime de Python en el momento del despliegue. El paquete publicado incluye el modelo Maia3 5M; las demás variantes de exportación no son opciones de ejecución a menos que sus archivos ONNX se proporcionen por separado.
Related MCP server: Chess MCP
Instalación
Requiere Node.js 20 o más reciente.
No necesita instalación — ejecútalo directamente con npx:
npx -y llm-chess-mcpEl modelo Maia3 ya viene incluido, así que no hay que instalar Python, torch ni binarios de motor. npx descarga el paquete en la primera ejecución y lo guarda en caché.
Para instalarlo permanentemente en su lugar:
npm install -g llm-chess-mcpCompilar desde el código fuente
pnpm install
pnpm build
pnpm testpnpm test:unit ejecuta la suite de pruebas unitarias. pnpm test:e2e compila primero y luego ejecuta las pruebas de transporte de MCP. pnpm check ejecuta todo el control local; usa pnpm release:check antes de publicar.
Mantenedores
Arquitectura describe los límites del runtime y de los servicios.
Comandos locales de calidad:
pnpm typecheck
pnpm test:coverage
pnpm contract:check
pnpm check
pnpm test:packagepnpm test:stress ejecuta la comprobación corta de concurrencia con el motor real. pnpm test:live consulta Lichess solo cuando LICHESS_TOKEN está definido; si no, se omite sin hacer ninguna petición de red.
Exportar Maia3 a ONNX (solo en tiempo de compilación)
Este paso necesita Python y PyTorch una sola vez. Descarga el checkpoint de Maia3, comprueba la reimplementación frente a la original y exporta models/maia3-5m.onnx.
uv venv .venv-maia3 --python 3.13
uv pip install --python .venv-maia3/bin/python -r scripts/requirements.txt
uv pip install --python .venv-maia3/bin/python "maia3 @ git+https://github.com/CSSLab/maia3.git@1e13597c42d4858b7cfd7cfdae01e297263364b2"
pnpm export:maia3 # -> models/maia3-5m.onnxEl .onnx resultante se commitea o se incluye en el paquete; los usuarios finales nunca necesitan Python ni torch.
Token de Lichess (opcional)
El explorador de aperturas ahora requiere autenticación. Genera un token de acceso personal en https://lichess.org/account/oauth/token/create y configúralo en .env:
cp .env.example .env
# set LICHESS_TOKEN=...Sin token, opening_explorer devuelve un aviso de desactivación; todas las demás herramientas funcionan.
Los filtros del explorador son estrictos. Las velocidades son ultraBullet, bullet, blitz, rapid, classical y correspondence; los segmentos de rating son 0, 1000, 1200, 1400, 1600, 1800, 2000, 2200 y 2500. masters no acepta ninguno de los filtros. Los filtros no válidos fallan localmente. Los fallos transitorios (red, timeout, 429 y 5xx) se reintentan una vez dentro de un presupuesto total de 12 segundos; las peticiones no válidas y el resto de respuestas 4xx no se reintentan.
Configuración en tu cliente MCP
opencode
Añádelo a opencode.json (proyecto) o ~/.config/opencode/opencode.json (global):
{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"llm-chess-mcp": {
"type": "local",
"command": ["npx", "-y", "llm-chess-mcp"],
"enabled": true,
"environment": {
"LICHESS_TOKEN": "your-token"
}
}
}
}Claude Code
Añádelo a .mcp.json (proyecto) o ~/.claude.json (global), o ejecuta:
claude mcp add llm-chess-mcp -- npx -y llm-chess-mcp{
"mcpServers": {
"llm-chess-mcp": {
"command": "npx",
"args": ["-y", "llm-chess-mcp"],
"env": {
"LICHESS_TOKEN": "your-token"
}
}
}
}Codex CLI
Añádelo a ~/.codex/config.toml:
[mcp_servers.llm-chess-mcp]
command = "npx"
args = ["-y", "llm-chess-mcp"]
[mcp_servers.llm-chess-mcp.env]
LICHESS_TOKEN = "your-token"O mediante la CLI:
codex mcp add llm-chess-mcp --command npx --args -y llm-chess-mcp --env LICHESS_TOKEN=your-tokenHerramientas
Tool | Descripción |
| Crea una partida (opcionalmente desde un FEN), devuelve |
| Elimina una partida y libera su sesión |
| Estado autoritativo: FEN, turno, revisión, indicadores de jaque/mate/tablas, historial, última jugada, enroque (ASCII opcional) |
| Juega una jugada (SAN o UCI) — la única herramienta que muta, con protección frente a posiciones obsoletas |
| Todas las jugadas legales con metadatos |
| Exporta la partida como PGN |
| Importa un PGN en una nueva partida |
| Líneas multipv de Stockfish (cp/mate/WDL + PV), con el preset |
| Probabilidades de jugada humana de Maia3 a un Elo objetivo |
| Evalúa una o más jugadas + cpLoss + clasificación |
| Herramienta principal: candidatas unificadas (objetiva + humana + de apertura) |
| Capa de conveniencia: candidatas ordenadas para una intención estratégica |
| Estadísticas reales de partidas humanas de Lichess |
Formato de resultado
structuredContent es el resultado de éxito canónico. Los fallos a nivel de gestor establecen isError y proporcionan structuredContent.error. Los fallos de validación de entrada los genera el SDK de MCP antes del gestor y usan su isError estándar de texto, sin structuredContent. En cualquier otro caso, content es solo un resumen breve legible y no debe interpretarse como datos.
Convenciones de puntuación
Las puntuaciones de Stockfish son desde la perspectiva del bando que mueve: cp positivo = el bando a mover está mejor;
mate N = el bando que mueve da mate en N.wdles[win, draw, loss]` en permille para el bando que mueve.move_candidatesdamoverCp(la perspectiva del que mueve: más alto = mejor para el jugador que elige la jugada) ywhiteCp(perspectiva fija de las baby White) para que el signo no se dé la vuelta.move_evaluatemuestra la puntuación desde la perspectiva del que mueve, máscpLoss(milesimas de peón perdidas con respecto a la mejor jugada) y la clasificación:best / excellent / good / inaccuracy / mistake / blunder.maia3Probes una probabilidad humana, no la calidad de la jugada. Una jugada con probabilidad alta puede ser objetivamente mala.
Estructura de las candidatas
move_candidates devuelve cada candidata con tres facetas independientes:
{
"uci": "g1f3",
"san": "Nf3",
"objective": { "rank": 1, "moverCp": 55, "whiteCp": 55, "cpLoss": 0, "moverMate": null, "wdl": [153, 844, 3] },
"human": { "maia3Prob": 0.62, "selfElo": 1500, "opponentElo": 1500 },
"opening": { "status": "available", "games": 18421, "frequency": 0.31 }
}objective— Stockfish: fuerza del motor, nunca mezclada con la probabilidad humana.moverCpestá en la perspectiva del que mueve (más alto = mejor para quien elige).human— Probabilidad condicional de Maia3 a un Elo objetivo.opening— Frecuencia empírica de Lichess (señal distinta de la de Maia3).
opening.status puede ser available, no_data (la API devuelve OK pero no hay partidas en esta posición), unavailable (timeout/429/401) o disabled (no token). La salida de Stockfish y de Maia3 siempre se devuelve en todos los casos.
move_candidates también devuelve moveSensitivity:
{ "moveSensitivity": { "level": "high", "topMoveSpreadCp": 245 } }level es low (<80cp de dispersión), medium (80–200cp) o high (≥200cp). La sensibilidad alta significa que elegir entre opciones plausibles puede cambiar materialmente la evaluación, lo que sirve para decidir si aflojar o jugar con precisión.
Niveles de análisis
Las herramientas de Stockfish aceptan un preset como analysis_level en lugar de parámetros UCI brutos:
Nivel | Depth | MultiPV |
| 8 | 5 |
| 15 | 8 |
| 22 | 10 |
Para uso avanzado se pueden seguir anulando con depth y multipv explícitos.
Protección de posición obsoleta
Cada lectura de estado devuelve una revision. game_play_move requiere expected_revision; si la partida ha avanzado desde tu última lectura, la jugada se rechaza:
{ "error": { "code": "STALE_POSITION", "message": "position changed: expected revision 2, current 3" } }Límites del runtime
A. Se mantienen hasta 1.000 sesiones de partida; las sesiones inactivas caducan después de una hora.
B. move_evaluate admite como máximo 10 jugadas por llamada.
C. Los PGN importados están limitados a 1 MiB y 4.096 pliegas (moves).
Intenciones
move_candidates_by_intent ordena candidatas para una intención elegida. Es una capa de comodidad por encima de move_candidates; los umbrales fijos de abajo son valores por defecto heurísticos, no una verdad absoluta:
Intención | Significado | Descripción |
| Jugada del motor más fuerte | |
| Fortaleza del motor pero plausible para humanos | |
| Lo que jugaría un humano típico en ese Elo | |
| Equilibrio entre fuerza y probabilidad humana | |
| Jugadas plausibles que reducen un poco la ventaja, sin cambiar el resultado esperado | |
| Inexactitudes plausibles que amplían de forma significativa las posibilidades del rival |
Esta herramienta ordena los candidatos pero no decide la jugada. Depende del contexto conversacional para la decisión final; no asignes de forma automática nivel de usuario a una intención.
Ejemplo de flujo
El bucle de juego normal hace tres llamadas:
create_game→game_idmove_candidates→ elegir jugadagame_play_move(conexpected_revision) → asignar la jugada
Aumenta solo cuando sea necesario:
position_analyze— líneas buenas objetivamentehuman_move_distribution— lo que un humano de ese Elo juegaopening_explorer— estadísticas de partidas realesmove_evaluate— puntuar una jugada específica (o comparar varias)
Verificación ONNX de Maia3
El modelo ONNX exportado se va a probar con regresión contra la implementación original de Maia3 en posiciones fijas y pares de Elo:
.venv-maia3/bin/python scripts/verify_maia3.py --model 5mComprueba el acuerdo en la jugada top1/topk y el error máximo de probabilidad para detectar regresiones de exportación/runtime. El maia3-5m.onnx incluido pasa con un 100% de acuerdo top-1 y top-5 y un error máximo de probabilidad <1e-4.
Verificación del paquete
Los artefactos del paquete se verifican localmente; este proyecto deliberadamente no tiene CI cloud.
Ejecuta pnpm check como gate determinista de offline. Usa pnpm test:package para empacar el proyecto, instala el tarball en un directorio temporal limpio y ejecuta el binario llm-chess-mcp instalado contra runtimes real de Stockfish y Maia. pnpm release:check ejecuta ambas comprobaciones junto con la auditoría de dependencias y el dry run del manifiesto.
Licencia y atribución
Este proyecto se distribuye bajo AGPL-3.0 (ver LICENSE).
Este paquete incluye y depende de componentes de terceros:
Componente | Licencia | Fuente |
Maia3 (Chessformer) | AGPL-3.0 | UofT CSSLab — Monroe et al., Chessformer: una arquitectura unificada para el modelado de ajedrez (ICLR 2026) |
Stockfish (via npm | GPL-3.0 | Los desarrolladores de Stockfish |
MIT | Microsoft | |
BSD-2-Clause | Jeff Hlywa |
El modelo Maia3 incluido (models/maia3-5m.onnx) se deriva de
UofTCSSLab/Maia3-5M en b6559de2398d7140b985f28fd2c19fb5e47ddabe.
La exportación ONNX es un paso de compilación (scripts/export_maia3.py); el tiempo de ejecución
no ejecuta ningún código Python de Maia3.
Available Tools
13 toolscreate_gameCreate Chess GameA
Create a new chess game and return its game_id. The server is the authoritative source of board state — never track the board yourself. Optionally pass a FEN to start from a custom position.
Inputs: fen. Returns: game_id, revision
delete_gameDelete Chess GameCDestructiveIdempotent
Delete a game and free its session.
Inputs: game_id (required). Returns: deleted, game_id
game_import_pgnImport Chess PGNA
Import a PGN into a new game. Returns a new game_id with the position after all PGN moves. Rejects malformed or illegal PGN.
Inputs: pgn (required). Returns: fen, turn, isDraw, game_id, +12 more
game_legal_movesList Legal Chess MovesARead-onlyIdempotent
List all legal moves in the current position (SAN, UCI, piece, capture, promotion).
Inputs: game_id (required). Returns: count, moves, game_id, revision
game_pgnExport Chess PGNBRead-onlyIdempotent
Export the current game as PGN.
Inputs: game_id (required). Returns: pgn, game_id, revision
game_play_movePlay Chess MoveADestructive
Play a move (SAN like 'e4' or UCI like 'e2e4') and return the resulting state. This is the ONLY tool that mutates the game. expected_revision is required: pass the revision from your most recent game_state/move_candidates read. If the game has advanced since then, the move is rejected with STALE_POSITION.
Inputs: move (required), game_id (required), expected_revision (required). Returns: fen, move, turn, isDraw, +13 more
game_stateGet Chess Game StateARead-onlyIdempotent
Return the authoritative state of a game: FEN, turn, revision, check/mate/draw flags, move history, last move, castling rights. Use this instead of remembering the board. Set include_ascii=true to also get a board diagram.
Inputs: game_id (required), include_ascii. Returns: fen, turn, board, isDraw, +13 more
human_move_distributionEstimate Human Chess MovesARead-onlyIdempotent
Return the Maia3 human-like move probability distribution for the current position, conditioned on a target Elo. Higher probability = more human-typical at that rating. This is NOT move quality — a high-probability move can still be objectively bad.
Inputs: game_id (required), elo, top_n, oppo_elo. Returns: elo, moves, game_id, oppo_elo, +1 more
move_candidatesGenerate Chess Move CandidatesARead-onlyIdempotent
The primary move-selection tool. Combine Stockfish objective evaluation (moverCp, whiteCp, cpLoss, mate, WDL), Maia3 human probability, and Lichess real-game statistics into a unified candidate list. moverCp is from the mover's perspective: higher = better for the player choosing the move. Use this before choosing a move; the final choice is yours.
Inputs: game_id (required), elo, sf_depth, lichess_db, +5 more. Returns: elo, fen, turn, game_id, +4 more
move_candidates_by_intentRank Chess Moves by IntentARead-onlyIdempotent
Convenience layer over move_candidates: rank candidates for a strategic intent. This tool RANKS candidates but does NOT choose a move — use the returned signals and conversation context to make the final decision. Do not map user skill mechanically to an intent. intents: best (strongest engine move), strong (engine-strong but human-plausible), natural (most human-typical), balanced (blend of strength and human-likeness), ease_off (human-plausible moves that modestly reduce advantage without changing the expected result), give_chance (human-plausible inaccuracies that meaningfully improve the opponent's chances).
Inputs: intent (required), game_id (required), elo, sf_depth, +6 more. Returns: elo, fen, turn, intent, +5 more
move_evaluateEvaluate Chess MovesARead-onlyIdempotent
Evaluate one or more moves with Stockfish without mutating the game. Pass a single move string or an array of moves to compare. Returns, for each move, the score after the move (from the mover's perspective), cpLoss vs the best move, and a classification (best/excellent/good/inaccuracy/mistake/blunder).
Inputs: move (required), game_id (required), depth. Returns: game_id, results, revision
opening_explorerQuery Lichess Opening ExplorerBRead-onlyIdempotent
Query the Lichess opening explorer for real human game statistics in the current position (requires LICHESS_TOKEN).
Inputs: game_id (required), db, speeds, ratings. Returns: db, black, draws, moves, +4 more
position_analyzeAnalyze Chess PositionARead-onlyIdempotent
Run Stockfish on the current position and return the top engine lines (multipv). Scores are from the side-to-move perspective: positive cp = side to move is better; mate N = side to move mates in N. wdl is [win, draw, loss] in permille for the side to move. Use analysis_level (fast/normal/deep) or explicit depth/multipv. Does NOT mutate the game.
Inputs: game_id (required), depth, multipv, analysis_level. Returns: fen, turn, lines, game_id, +2 more
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 13 tools
Game lifecycle tools are clearly distinct: create, delete, state, move, legal moves, PGN export/import. The move-analysis tools overlap somewhat—position_analyze, move_evaluate, move_candidates, and move_candidates_by_intent all return evaluation-like signals—but their descriptions clarify different purposes: raw engine lines, per-move comparison, unified candidate selection, and intent-based ranking. An agent could hesitate between these, but they are not truly interchangeable.
Some names follow verb_noun (create_game, delete_game), while others are noun phrases or prefixed differently (game_state, game_pgn, game_import_pgn, position_analyze, opening_explorer). The move_* group is predictable, but the overall naming is a mix of conventions. Names are still readable and snake_case consistent, so the inconsistency is moderate rather than chaotic.
Thirteen tools is well within the ideal range and appropriate for a chess server that handles game lifecycle, PGN import/export, legal move queries, engine analysis, human-move modeling, and opening statistics. Each tool has a defined role, and the count does not feel bloated or thin.
The surface covers the full lifecycle: create, read state, mutate via play move, legal moves, delete, and PGN import/export. Analysis coverage is also strong: Stockfish lines, move evaluation, human move distributions, unified candidates, intent-based ranking, and opening explorer. There are no obvious dead ends for playing or analyzing a chess game.
Maintenance
Related MCP Connectors
MCP server exposing the Backtest360 engine API as tools for AI agents.
MCP server for OpenMM — exposes market data, account, trading, and strategy tools to AI agents
MCP server for building and testing AI agents with multi-model experimentation and insights.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceA Model Context Protocol server that lets your AI talk to Stockfish. Because apparently we needed to make chess engines even more accessible to our silicon overlords.16MIT
- AlicenseNot gradedqualityDmaintenanceA powerful chess engine and game server built with the Model Context Protocol (MCP). Play chess against AI, analyze positions, and integrate chess functionality into your AI applications.1MIT
- AlicenseAqualityDmaintenanceA hybrid AI chess coach MCP server that uses Stockfish for grounded evaluation and LLM for natural-language coaching, enabling game analysis, weakness diagnosis, and personalized drills from your own games.65MIT
- FlicenseNot gradedqualityDmaintenanceAn MCP server that exposes Stockfish chess analysis to LLM chat clients, enabling move analysis, game review, and explanation of engine choices.-