=============== LIBRARY RULES =============== From library maintainers: - The engine is not bundled: install a UCI engine separately and pass its path as the first argument -- uvx chess-uci-mcp@latest /usr/local/bin/stockfish - Any UCI-compatible engine works, not only Stockfish; Leela Chess Zero (lc0) is covered by the test suite - Six tools are served: analyze, get_best_move, set_position, engine_info, get_engine_options, set_engine_options - Startup UCI options use a repeatable flag taking two values: -o Threads 4 -o Hash 128 - Options can also be read and changed while the server runs, with get_engine_options and set_engine_options - analyze always requires an explicit FEN; set_position stores a position for the next get_best_move only - analyze reports the score from White's perspective: a float in pawns, or the string mateN for a forced mate - Thinking time defaults to 1000 ms; override it per call with time_ms, or for the whole server with --think-time ### Usage example for set_position and get_best_move Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/engine.md Shows how to start the engine, set a position with moves, get the best move with a custom time limit, and stop the engine in a finally block. The example uses Stockfish at /usr/local/bin/stockfish and prints the best move (e.g., "g1f3"). ```python engine = UCIEngine("/usr/local/bin/stockfish") await engine.start() try: await engine.set_position(fen=None, moves=["e2e4", "e7e5"]) # then Black to move best = await engine.get_best_move(time_ms=300) print(best) # e.g. "g1f3" finally: await engine.stop() ``` -------------------------------- ### Development setup commands Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/README.md Commands to clone the repository, create a virtual environment, install the package, run tests, and check code style. Includes commands for Unix/macOS and Windows. ```bash git clone https://github.com/AnglerfishChess/chess-uci-mcp.git # ... or # git clone git@github.com:AnglerfishChess/chess-uci-mcp.git cd chess-uci-mcp # Create a virtual environment uv venv --python python3.13 # Activate the virtual environment source .venv/bin/activate # On Unix/macOS # or .venv\Scripts\activate # On Windows # Install the package in development mode # uv pip install -e . # or, with development dependencies uv pip install -e ".[dev]" # Resync the packages: uv sync --extra=dev # Run tests pytest # Check code style ruff check ``` -------------------------------- ### start Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/engine.md Starts the engine process, performs the UCI handshake, starts a new game, and applies startup options. ```APIDOC ## `start` ```python async def start(self) -> None: ``` **Source:** `chess_uci_mcp/engine.py:104` Starts the engine process, performs the UCI handshake, starts a new game, and applies every startup option (coercing each value with `_coerce` to the type the option declares). Unknown option names are logged as warnings and skipped. If any option was applied, `is_ready()` is awaited. ### Returns `None` on success. The engine is then usable and `_ready` is `True`. ### Throws | Error | Condition | |-------|-----------| | `RuntimeError("Failed to start engine: {e}")` | Raised from any exception during handshake, `new_game`, option coercion (`int(str(value))` on a non-numeric `spin` value), or `set_option`. The engine process is killed first (`engine.kill()`). See [errors](../errors.md). | ``` -------------------------------- ### Run chess-uci-mcp with uvx (recommended) Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/README.md Configure the MCP server to run chess-uci-mcp via uvx, which automatically creates a virtual environment and installs dependencies. The engine path is passed as an argument; this example uses the default Stockfish path for macOS Brew. ```json "mcpServers": { "chess-uci-mcp": { "command": "uvx", "args": ["chess-uci-mcp@latest", "/usr/local/bin/stockfish"] } } ``` -------------------------------- ### Handle engine start failure Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/engine.md Error handling example: starting the engine against a bad binary raises RuntimeError with a message starting with 'Failed to start engine:'. The engine process is killed first. ```python engine = UCIEngine("/nonexistent/engine") try: await engine.start() except RuntimeError as e: print("Engine failed to start:", e) # "Failed to start engine: ..." ``` -------------------------------- ### start method signature Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/engine.md Signature of the start method. Starts the engine process, performs the UCI handshake, starts a new game, and applies startup options. Raises RuntimeError on failure. ```python async def start(self) -> None: ``` -------------------------------- ### Example: setting UCI options with set_options Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/engine.md Example usage of set_options, showing how to set options, handle applied and error results, and clean up the engine. ```python engine = UCIEngine("/usr/local/bin/stockfish") await engine.start() try: applied, errors = await engine.set_options({"Hash": 128, "Threads": 4, "Bogus": 1}) print(applied) # {"Hash": 128, "Threads": 4} print(errors) # {"Bogus": "Option 'Bogus' is not supported by this engine"} finally: await engine.stop() ``` -------------------------------- ### Usage example: importing and using chess_uci_mcp Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/chess_uci_mcp.md Shows how to import the package and use UCIEngine and ChessUCIBridge. The example creates an engine and a bridge with a think_time of 200 milliseconds. ```python import chess_uci_mcp from chess_uci_mcp.engine import UCIEngine from chess_uci_mcp.server import ChessUCIBridge print(chess_uci_mcp.__version__) # 0.3.0 engine = UCIEngine("/usr/local/bin/stockfish") bridge = ChessUCIBridge("/usr/local/bin/stockfish", think_time=200) ``` -------------------------------- ### ChessUCIBridge instantiation example Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/server.md Example of creating a ChessUCIBridge instance with a custom think_time and engine options. The comment shows the resulting attribute values. ```python bridge = ChessUCIBridge("/usr/local/bin/stockfish", think_time=200, Threads=4, Hash=128) # default_think_time == 200, engine_options == {"Threads": 4, "Hash": 128} ``` -------------------------------- ### Analyze a position with UCIEngine Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/engine.md Example usage of UCIEngine: start, analyze a position, and stop in a finally block. Prints best_move, score, and pv. ```python engine = UCIEngine("/usr/local/bin/stockfish") await engine.start() try: analysis = await engine.analyze_position( "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", time_ms=500, ) print(analysis["best_move"], analysis["score"], analysis["pv"]) finally: await engine.stop() ``` -------------------------------- ### set_engine_options failure response example Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/server.md Example JSON response from set_engine_options when some options fail. success is True only if errors is empty. ```json { "success": false, "applied_options": {"Threads": 4}, "errors": {"Hash": "Value 256 is above maximum 128"} } ``` -------------------------------- ### engine_info response example Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/server.md Example JSON response from the engine_info tool. Shows the engine path, UCI identity (keys present only if reported), and the constructor engine_options dict. ```json { "path": "/usr/local/bin/stockfish", "id": {"name": "Stockfish 17", "author": "the Stockfish developers"}, "configured_options": {"Threads": 4, "Hash": 128} } ``` -------------------------------- ### Configure MCP client with chess-uci-mcp Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/main.md Example MCP client configuration that invokes the chess-uci-mcp console script via uvx. It passes the engine path and UCI options as command-line arguments, including a think time of 2000 ms. ```json "mcpServers": { "chess-uci-mcp": { "command": "uvx", "args": ["chess-uci-mcp@latest", "/usr/local/bin/stockfish", "-o", "Threads", "4", "-o", "Hash", "128", "--think-time", "2000"] } } ``` -------------------------------- ### Catch RuntimeError("Failed to start engine: {e}") Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/errors.md Use this snippet to catch the RuntimeError raised when UCIEngine.start fails during the UCI handshake, new_game, startup option coercion, or set_option. The error message starts with "Failed to start engine: " and includes the underlying exception. ```python bridge = ChessUCIBridge("/bad/engine") try: await bridge.start() except RuntimeError as e: print(e) # "Failed to start engine: ..." ``` -------------------------------- ### Initialize ChessUCIBridge and call engine_info tool Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/server.md Use this snippet to start the Stockfish engine and call the engine_info tool. The bridge is initialized with the engine path and think time. The _ensure_engine_started method is internal; you can also call a tool first. The bridge is stopped in a finally block. ```python import asyncio from chess_uci_mcp.server import ChessUCIBridge async def main(): bridge = ChessUCIBridge("/usr/local/bin/stockfish", think_time=100) try: await bridge._ensure_engine_started() # internal; or call a tool first info = await bridge.mcp.call_tool("engine_info", {}) print(info) finally: await bridge.stop() asyncio.run(main()) ``` -------------------------------- ### Analyze Tool Request Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/endpoints.md Example JSON-RPC request sent by an MCP client to invoke the analyze tool with a FEN string and thinking time. ```json {"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "analyze", "arguments": {"fen": "6k1/5ppp/8/8/8/8/8/R5K1 w - - 0 1", "time_ms": 100}}} ``` -------------------------------- ### Analyze Tool Response Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/endpoints.md Example response content from the analyze tool, showing a forced mate in one move. ```json [{"type": "text", "text": "{\"depth\": 30, \"score\": \"mate1\", \"pv\": [\"a1a8\"], \"best_move\": \"a1a8\"}"}] ``` -------------------------------- ### get_best_move Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/engine.md Calculates the best move from the position last stored by set_position (defaults to the starting position). Runs engine.play(...) with Limits(movetime=time_ms / 1000) and the same _ANSWER_MARGIN wait budget as analyze_position. ```APIDOC ## `get_best_move` ```python async def get_best_move(self, time_ms: int = 1000) -> str: ``` **Source:** `chess_uci_mcp/engine.py:204` Calculates the best move from the position last stored by [`set_position`](#set_position) (defaults to the starting position). Runs `engine.play(...)` with `Limits(movetime=time_ms / 1000)` and the same `_ANSWER_MARGIN` wait budget as `analyze_position`. ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `time_ms` | `int` | no | `1000` | Thinking time in milliseconds. | ### Returns `str` — the best move in UCI format (e.g. `"e2e4"`), or `""` (empty string) if the engine returned no best move (`answer.best` was `None`). ### Throws | Error | Condition | |-------|-----------| | `RuntimeError("Engine not started")` | Engine not started. | | `ValueError` | Propagated from `_game` when the stored FEN/moves cannot be read. | ### Example ```python engine = UCIEngine("/usr/local/bin/stockfish") await engine.start() try: await engine.set_position(fen=None, moves=["e2e4", "e7e5"]) # then Black to move best = await engine.get_best_move(time_ms=300) print(best) # e.g. "g1f3" finally: await engine.stop() ``` ``` -------------------------------- ### get_engine_options Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/endpoints.md Gets all available UCI engine options with their metadata and current values. ```APIDOC ## get_engine_options ### Description Gets all available UCI engine options with their metadata and current values. ### Input None. ### Output - `options` (object) - An object mapping option names to objects with `metadata` and `current_value`. - `metadata` (object) - Contains `name`, `type`, `default`, `min`, `max`, `var` fields. - `current_value` (any) - The current value of the option. ### Errors - `RuntimeError` - If the engine cannot be started. ``` -------------------------------- ### get_best_move method signature Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/engine.md Async method that calculates the best move from the position last stored by set_position (defaults to starting position). Runs engine.play(...) with Limits(movetime=time_ms / 1000) and the same _ANSWER_MARGIN wait budget as analyze_position. Returns the best move in UCI format or an empty string if no best move was returned. ```python async def get_best_move(self, time_ms: int = 1000) -> str: ``` -------------------------------- ### Register get_best_move MCP tool Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/server.md Registers the 'get_best_move' MCP tool. If fen is provided, it is validated and stored as the engine position; otherwise the last set position or the starting position is used. Returns the best move as a UCI string (possibly empty). ```python @self.mcp.tool("get_best_move", description="Get the best move for a chess position.") async def get_best_move(fen: str | None = None, time_ms: int | None = None) -> str: ``` -------------------------------- ### Run and stop ChessUCIBridge with error handling Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/main.md Shows the behavior of run_bridge: it creates a ChessUCIBridge with the engine path, think time, and UCI options as constructor keywords, starts it, and gracefully stops on KeyboardInterrupt or in the finally block. The bridge stops when the stdio transport closes. ```python bridge = ChessUCIBridge(engine_path, think_time=think_time, **uci_options) try: await bridge.start() except KeyboardInterrupt: logger.info("Keyboard interrupt received, shutting down") finally: logger.info("Shutting down bridge") await bridge.stop() ``` -------------------------------- ### engine_info Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/endpoints.md Gets information about the chess engine, including its path, identification, and configured options. ```APIDOC ## engine_info ### Description Gets information about the chess engine. ### Input None (empty arguments object). ### Output - `path` (string) - Path to the engine executable. - `id` (object) - Object with optional `name`/`author` strings. - `configured_options` (object) - Mapping of option names to values. ### Errors - `RuntimeError` - If the engine cannot be started. ``` -------------------------------- ### get_best_move Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/endpoints.md MCP tool to get the best move for a chess position, returning a UCI move string. ```APIDOC ## Tool: `get_best_move` ### Description Gets the best move for a chess position, either from a provided FEN or from the last set position. ### Method `tools/call` (MCP) ### Endpoint `tools/call` with `name: "get_best_move"` ### Parameters #### Input Arguments - **`fen`** (string | null) - Optional - If given, validated and stored as the engine position; otherwise the position last set with `set_position` (or the starting position) is used. - **`time_ms`** (integer | null) - Optional - Thinking time in ms; defaults to the bridge `default_think_time` (1000 unless configured). ### Request Example ```json {"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "get_best_move", "arguments": {"fen": "6k1/5ppp/8/8/8/8/8/R5K1 w - - 0 1", "time_ms": 100}}} ``` ### Response #### Success Response - **`result`** (string) - Best move in UCI format (e.g. `"e2e4"`); `""` if the engine offered none. #### Response Example ```json [{"type": "text", "text": "\"e2e4\""}] ``` ### Errors - `ValueError` - On an unreadable `fen`. - `RuntimeError` - If the engine cannot be started. ``` -------------------------------- ### Catch RuntimeError("Engine not started") Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/errors.md Use this snippet to catch the RuntimeError raised when engine-touching UCIEngine methods are invoked while the engine is not running. The error message is exactly "Engine not started". ```python try: await engine.get_best_move(500) except RuntimeError as e: assert str(e) == "Engine not started" ``` -------------------------------- ### set_position Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/engine.md Stores a position on the wrapper for the next get_best_move call. The starting position is used if fen is None; moves are replayed from that position. ```APIDOC ## `set_position` ```python async def set_position(self, fen: str | None = None, moves: list[str] | None = None) -> None: ``` **Source:** `chess_uci_mcp/engine.py:186` Stores a position on the wrapper for the next [`get_best_move`](#get_best_move) call. The starting position is used if `fen` is `None`; `moves` are replayed from that position. ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `fen` | `str \| None` | no | `None` | FEN to start from; `None` means the standard starting position. | | `moves` | `list[str] \| None` | no | `None` | Moves in UCI format to play from that position. | ### Returns `None`. ### Throws | Error | Condition | |-------|-----------| | `RuntimeError("Engine not started")` | Engine not started. | Note: FEN/move validity is only checked later, when a search actually plays the position (in `_game`), not at call time. ``` -------------------------------- ### set_position method signature Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/engine.md Async method that stores a position (FEN and optional moves) on the wrapper for the next get_best_move call. If fen is None, the standard starting position is used. FEN/move validity is only checked later during a search, not at call time. ```python async def set_position(self, fen: str | None = None, moves: list[str] | None = None) -> None: ``` -------------------------------- ### Run chess-uci-mcp with uv from local clone Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/README.md Configure the MCP server to run chess-uci-mcp from a local repository clone using uv run. The engine path is passed as an argument. ```json "mcpServers": { "chess-uci-mcp": { "command": "uv", "args": ["run", "chess-uci-mcp", "/usr/local/bin/stockfish"] } } ``` -------------------------------- ### UCIEngine.__init__ Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/engine.md Constructor for the UCIEngine class. Initializes the engine with the executable path and optional startup options. ```APIDOC ## UCIEngine.__init__ ### Description Initializes a new UCIEngine instance with the path to a UCI chess engine executable and optional startup options. ### Method Constructor ### Parameters #### Constructor Parameters - **engine_path** (str) - Required - Path to the UCI engine executable. - **options** (dict[str, Any] | None) - Optional - Engine options to set at startup (name → value; values may be text, coerced per option type). Default: None. ### Throws None at construction; startup errors surface in start(). ``` -------------------------------- ### Call analyze tool with sample FEN Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/server.md Calls the 'analyze' tool with a sample FEN and prints the JSON response. The output contains depth, score, pv, and best_move. ```python result = await bridge.mcp.call_tool("analyze", {"fen": "4k3/8/8/8/8/8/8/4K3 w - - 0 1", "time_ms": 100}) print(result[0].text) # JSON: {"depth": ..., "score": ..., "pv": [...], "best_move": "..."} ``` -------------------------------- ### get_available_options Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/engine.md Returns a dictionary mapping each option name to its metadata. ```APIDOC ## get_available_options ### Description Returns a dictionary mapping each option name to its metadata. ### Method N/A (Python method) ### Endpoint N/A (Python method) ### Parameters None ### Returns `dict[str, OptionMetadata]` — maps each option name (as spelled by the engine) to its metadata, see [types.md](../types.md) for the `OptionMetadata` fields: | Field | Type | Description | |-------|------|-------------| | `name` | `str` | Option name. | | `type` | `str` | `"check"`, `"spin"`, `"combo"`, `"button"` or `"string"`. | | `default` | `ConfigValue` | Default value. | | `min` | `int \| None` | Only for `"spin"`. | | `max` | `int \| None` | Only for `"spin"`. | | `var` | `list[str] \| None` | Only for `"combo"` (allowed values). | ### Throws | Error | Condition | |-------|-----------| | `RuntimeError("Engine not started")` | Engine not started. | ``` -------------------------------- ### Pass engine options (Threads, Hash) with uvx Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/README.md Extends the uvx configuration to pass engine options to Stockfish. Use the -o flag followed by the option name and value; here Threads is set to 4 and Hash to 128. ```json "mcpServers": { "chess-uci-mcp": { "command": "uvx", "args": [ "chess-uci-mcp@latest", "/usr/local/bin/stockfish", "-o", "Threads", "4", "-o", "Hash", "128" ] } } ``` -------------------------------- ### Define Click CLI for chess-uci-mcp main Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/main.md Defines the Click command-line interface for the chess-uci-mcp console script. It accepts a required engine path, repeatable UCI options, a think time defaulting to 1000 ms, and a debug flag. The engine path is validated with click.Path(exists=True). ```python @click.command() @click.argument("engine_path", type=click.Path(exists=True)) @click.option( "--uci-option", "-o", multiple=True, type=(str, str), metavar="NAME VALUE", help="Set a UCI option (e.g., -o Threads 4)", ) @click.option("--think-time", default=1000, type=int, help="Default thinking time in ms") @click.option("--debug/--no-debug", default=False, help="Enable debug logging") def main( engine_path: str, uci_option: list[tuple[str, str]], think_time: int = 1000, debug: bool = False, ) -> None: ``` -------------------------------- ### Register engine_info MCP tool Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/server.md Registers the 'engine_info' MCP tool. Takes no arguments and returns engine information including path, id, and configured_options. ```python @self.mcp.tool("engine_info", description="Get information about the chess engine.") async def engine_info() -> EngineInfo: ``` -------------------------------- ### Pass engine options (Threads, Hash) with uv Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/README.md Extends the uv configuration to pass engine options to Stockfish. Use the -o flag followed by the option name and value; here Threads is set to 4 and Hash to 128. ```json "mcpServers": { "chess-uci-mcp": { "command": "uv", "args": [ "run", "chess-uci-mcp", "/usr/local/bin/stockfish", "-o", "Threads", "4", "-o", "Hash", "128" ] } } ``` -------------------------------- ### Register set_engine_options MCP tool Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/server.md Registers the 'set_engine_options' MCP tool. Takes an options dict (e.g. {"Hash": 256, "Threads": 4}) and delegates to UCIEngine.set_options. An empty dict short-circuits to success with no errors. ```python @self.mcp.tool( "set_engine_options", description="Set one or more UCI engine options at runtime.", ) async def set_engine_options(options: dict[str, Any]) -> SetEngineOptionsResult: ``` -------------------------------- ### Register get_engine_options MCP tool Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/server.md Registers the 'get_engine_options' MCP tool. Takes no arguments and returns a dict of options with metadata and current_value (explicitly set value or declared default). ```python @self.mcp.tool( "get_engine_options", description="Get all available UCI engine options with their metadata and current values.", ) async def get_engine_options() -> GetEngineOptionsResult: ``` -------------------------------- ### ChessUCIBridge constructor Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/server.md Constructor for ChessUCIBridge. Takes the path to the UCI engine executable and optional keyword arguments. The special key 'think_time' is popped with default 1000 and becomes 'default_think_time'; other keywords are kept in 'engine_options' and passed to UCIEngine as startup options. ```python def __init__(self, engine_path: str, **options): ``` -------------------------------- ### set_engine_options Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/server.md Sets UCI engine options. Takes an options dict and delegates to UCIEngine.set_options. Returns success, applied_options, and errors. ```python @self.mcp.tool( "set_engine_options", description="Set UCI engine options.", ) async def set_engine_options(options: dict) -> SetEngineOptionsResult: ``` -------------------------------- ### UCIEngine Constructor Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/engine.md Constructor signature for the UCIEngine class. ```python def __init__(self, engine_path: str, options: dict[str, Any] | None = None): ``` -------------------------------- ### Version synchronization commands Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/README.md Commands to sync the version from pyproject.toml to other files, and to check for drift without modifying files. ```bash uv sync --extra=dev # updates uv.lock, keeping the dev tools installed uv run python .claude/skills/releasing/scripts/sync_version.py ``` -------------------------------- ### set_options Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/engine.md Sets one or more UCI options at runtime. Each option is resolved case-insensitively, validated, and sent to the engine. Returns a tuple of applied options and errors. ```APIDOC ## set_options ### Description Sets one or more UCI options at runtime. Each option is resolved case-insensitively against the engine's declarations, validated against its declared type/constraints, then sent with `engine.set_option`. A failing value never stops the others from being attempted. After any success, the tracked values are updated and `is_ready()` is awaited. ### Method async def set_options(self, options: dict[str, ConfigValue]) -> tuple[dict[str, ConfigValue], dict[str, str]] ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `options` | `dict[str, ConfigValue]` | yes | — | Option name → value to apply. | ### Returns `tuple[dict[str, ConfigValue], dict[str, str]]`: - First element `applied`: name → value for every option that was applied. - Second element `errors`: name → message for every option that failed. Per-option error messages: | Condition | Error message | |-----------|---------------| | Unknown option name | `"Option '{name}' is not supported by this engine"` | | `check` option with a non-`bool` | `"Expected boolean value for check option, got {typename}"` | | `spin` option with a non-`int` (or `bool`) | `"Expected integer value for spin option, got {typename}"` | | `spin` value below `min` | `"Value {value} is below minimum {min}"` | | `spin` value above `max` | `"Value {value} is above maximum {max}"` | | `combo` value not in `var` | `"Value '{value}' not in allowed values: {vars}"` | | `string` option with a non-`str`/non-`None` value | `"Expected string value for string option, got {typename}"` | | `engine.set_option` raises `ValueError` | `str(e)` | `"button"`-type options pass validation (they trigger an action and take no persistent value). ### Throws | Error | Condition | |-------|-----------| | `RuntimeError("Engine not started")` | Engine not started. | (Nothing else is raised; per-option failures are returned in `errors`.) ### Example ```python engine = UCIEngine("/usr/local/bin/stockfish") await engine.start() try: applied, errors = await engine.set_options({"Hash": 128, "Threads": 4, "Bogus": 1}) print(applied) # {"Hash": 128, "Threads": 4} print(errors) # {"Bogus": "Option 'Bogus' is not supported by this engine"} finally: await engine.stop() ``` ``` -------------------------------- ### set_engine_options partial failure request and response Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/endpoints.md Shows a request to set engine options with one valid and one invalid value, and the corresponding response. The response reports partial failure: the valid option is applied, while the invalid one is listed in errors with the message 'Expected integer value for spin option, got str'. ```json {"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "set_engine_options", "arguments": {"options": {"Threads": 4, "Hash": "not_a_number"}}}} ``` ```json [{"type": "text", "text": "{\"success\": false, \"applied_options\": {\"Threads\": 4}, \"errors\": {\"Hash\": \"Expected integer value for spin option, got str\"}}"}] ``` -------------------------------- ### Query MCP registry for chess-uci-mcp Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/README.md Curl command to search the MCP registry for the chess-uci-mcp server. ```bash curl -s "https://registry.modelcontextprotocol.io/v0/servers?search=chess-uci-mcp&limit=3" ``` -------------------------------- ### set_options method signature Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/engine.md The method signature for set_options, which takes a dictionary of option names to values and returns a tuple of applied options and errors. ```python async def set_options(self, options: dict[str, ConfigValue]) -> tuple[dict[str, ConfigValue], dict[str, str]]: ``` -------------------------------- ### analyze Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/endpoints.md MCP tool to analyze a chess position from a FEN string, returning depth, score, principal variation, and best move. ```APIDOC ## Tool: `analyze` ### Description Analyzes a chess position specified by a FEN string, returning the engine's evaluation, principal variation, and best move. ### Method `tools/call` (MCP) ### Endpoint `tools/call` with `name: "analyze"` ### Parameters #### Input Arguments - **`fen`** (string) - Required - FEN string of the position to analyze; must parse via `esca.Position.from_fen`. - **`time_ms`** (integer | null) - Optional - Thinking time in ms; defaults to the bridge `default_think_time` (1000 unless configured). ### Request Example ```json {"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "analyze", "arguments": {"fen": "6k1/5ppp/8/8/8/8/8/R5K1 w - - 0 1", "time_ms": 100}}} ``` ### Response #### Success Response - **`depth`** (integer) - Search depth reached. - **`score`** (number | string | null) - Evaluation in pawns from White's point of view; `"mateN"` for a forced mate. - **`pv`** (array) - Principal variation as a list of UCI moves. - **`best_move`** (string | null) - Best move in UCI format. #### Response Example ```json [{"type": "text", "text": "{\"depth\": 30, \"score\": \"mate1\", \"pv\": [\"a1a8\"], \"best_move\": \"a1a8\"}"}] ``` ### Errors - `ValueError` - `"Invalid FEN string: {fen}"` - `RuntimeError` - If the engine cannot be started. ``` -------------------------------- ### Package version constant Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/chess_uci_mcp.md Defines the package version string. It is kept in sync with pyproject.toml and server.json by the release script. ```python __version__ = "0.3.0" ``` -------------------------------- ### Register analyze MCP tool Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/server.md Registers the 'analyze' MCP tool. Requires a valid FEN string; optional time_ms defaults to bridge.default_think_time. Returns a dict with depth, score, pv, and best_move, where score is from White's perspective (float or "mateN"). ```python @self.mcp.tool("analyze", description="Analyze a chess position specified by FEN string.") async def analyze(fen: str, time_ms: int | None = None) -> dict[str, Any]: ``` -------------------------------- ### Run bridge programmatically with asyncio Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/main.md Programmatic usage of run_bridge: it imports the function and runs it with asyncio.run, passing the engine path, a dictionary of UCI options, and a think time. This bypasses the CLI and directly invokes the bridge. ```python import asyncio from chess_uci_mcp.__main__ import run_bridge asyncio.run(run_bridge("/usr/local/bin/stockfish", {"Threads": "4"}, think_time=1000)) ``` -------------------------------- ### Register set_position MCP tool Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/server.md Registers the 'set_position' MCP tool. Stores the position and optional moves for the next get_best_move. Raises ValueError if moves is truthy and not a list. Returns {"success": True}. ```python @self.mcp.tool("set_position", description="Set the current chess position.") async def set_position(fen: str | None = None, moves: list[str] | None = None) -> dict[str, bool]: ``` -------------------------------- ### GetEngineOptionsResult TypedDict (get_engine_options tool) Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/types.md Return type for the get_engine_options MCP tool mapping option names to detailed option info. ```python class GetEngineOptionsResult(TypedDict): """Return type for get_engine_options tool.""" options: dict[str, OptionInfo] ``` -------------------------------- ### EngineInfo TypedDict (engine_info tool) Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/types.md Return type for the engine_info MCP tool containing path, EngineId, and configured options. The path is the executable given to ChessUCIBridge. ```python class EngineInfo(TypedDict): """Return type for engine_info tool.""" path: str id: EngineId configured_options: dict[str, ConfigValue] ``` -------------------------------- ### Consume per-option errors from set_options Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/errors.md Use this snippet to handle errors returned by UCIEngine.set_options. It returns a tuple (applied, errors) instead of raising exceptions for bad option values. The errors dictionary contains messages keyed by option name, such as 'Expected integer value for spin option, got str' for a spin option with a non-integer value. ```python applied, errors = await engine.set_options({"Hash": "x"}) if errors: print(errors["Hash"]) # "Expected integer value for spin option, got str" ``` -------------------------------- ### stop Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/engine.md Sends `quit` to the engine and releases the handle. Errors during shutdown are logged but not raised. ```APIDOC ## `stop` ```python async def stop(self) -> None: ``` **Source:** `chess_uci_mcp/engine.py:138` Sends `quit` to the engine and releases the handle. Errors during shutdown are logged but not raised. ### Returns `None`. After this, `_ready` is `False` and `engine` is `None`. ``` -------------------------------- ### SetEngineOptionsResult TypedDict (set_engine_options tool) Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/types.md Return type for the set_engine_options MCP tool indicating success, applied options, and errors per option. The errors dict maps option names to error messages. ```python class SetEngineOptionsResult(TypedDict): """Return type for set_engine_options tool.""" success: bool applied_options: dict[str, ConfigValue] errors: dict[str, str] # option_name -> error_message ``` -------------------------------- ### OptionInfo TypedDict class definition Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/types.md Represents an option's metadata plus its current value. The 'current_value' is computed as the explicitly set value, falling back to the metadata default. ```python class OptionInfo(TypedDict): """Full information about an option including current value.""" metadata: OptionMetadata current_value: ConfigValue ``` -------------------------------- ### analyze_position method signature Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/engine.md Signature of the analyze_position method. Analyzes the given FEN position and returns the best line. Uses a movetime limit and a wait budget. ```python async def analyze_position(self, fen: str, time_ms: int = 1000) -> dict[str, Any]: ``` -------------------------------- ### Define run_bridge async function signature Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/main.md Signature of the asynchronous bridge runner. It takes the engine path, a dictionary of UCI options, and a think time in milliseconds, and returns None when the MCP server stops. ```python async def run_bridge(engine_path: str, uci_options: dict[str, str], think_time: int) -> None: ``` -------------------------------- ### get_current_option_values Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/engine.md Returns the explicitly set option values. Options that were never set use their engine defaults, available via get_available_options. The returned dict is a copy. ```APIDOC ## get_current_option_values ### Description Returns the explicitly set option values. Options that were never set use their engine defaults, available via [`get_available_options`](#get_available_options). The returned dict is a copy. ### Method N/A (Python method) ### Endpoint N/A (Python method) ### Parameters None ### Returns `dict[str, ConfigValue]` — option name → currently configured value (see [types.md](../types.md)). Note: unlike the other accessors, this does **not** raise when the engine is not started. ``` -------------------------------- ### analyze_position Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/engine.md Analyzes a chess position given by FEN and returns the best line found, including depth, score, principal variation, and best move. ```APIDOC ## `analyze_position` ```python async def analyze_position(self, fen: str, time_ms: int = 1000) -> dict[str, Any]: ``` **Source:** `chess_uci_mcp/engine.py:150` Analyzes the position given by `fen` and returns the best line found. The game is built fresh from the FEN (see `_game`); the search runs with `esca.uci.Limits(movetime=time_ms / 1000)` and a wait budget of `time_ms / 1000 + _ANSWER_MARGIN` seconds. ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `fen` | `str` | yes | — | FEN string of the position to analyze. | | `time_ms` | `int` | no | `1000` | Thinking time in milliseconds for the search. | ### Returns `dict[str, Any]` with the following keys: | Key | Type | Description | |-----|------|-------------| | `depth` | `int` | Search depth of the best line (reported by the engine); `0` if the engine reported none. | | `score` | `float \| str \| None` | Evaluation in **pawns from White's point of view** (`float`), `"mateN"` for a forced mate (positive `N` means White mates, `"mate-1"` means Black mates in 1), or `None` if the engine reported no score. Computed by `_format_score`: `sign = 1 if side_to_move == "w" else -1`; mate → `f"mate{sign * info.mate}"`; centipawns → `sign * info.cp / 100.0`. | | `pv` | `list[str]` | Principal variation as UCI move strings (e.g. `["e2e4", "e7e5"]`), spelled from the analyzed position; cut short at the first move that cannot be played. Castling is spelled king-two-squares (e.g. `"e1g1"`). | | `best_move` | `str \| None` | First move of the `pv`; `None` if the line is empty. | If the engine produced no lines at all, returns the literal `{"depth": 0, "score": None, "pv": [], "best_move": None}`. ### Throws | Error | Condition | |-------|-----------| | `RuntimeError("Engine not started")` | `start()` has not succeeded or the engine was stopped. | | `ValueError` | Propagated from `_game` when the FEN cannot be read by `esca.Game.from_fen`. | ### Example ```python engine = UCIEngine("/usr/local/bin/stockfish") await engine.start() try: analysis = await engine.analyze_position( "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", time_ms=500, ) print(analysis["best_move"], analysis["score"], analysis["pv"]) finally: await engine.stop() ``` Error handling — starting the engine against a bad binary: ```python engine = UCIEngine("/nonexistent/engine") try: await engine.start() except RuntimeError as e: print("Engine failed to start:", e) # "Failed to start engine: ..." ``` ``` -------------------------------- ### Catch ValueError for moves not a list Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/errors.md Use this snippet to verify that the MCP tool 'set_position' raises a ValueError with the exact message 'Moves must be a list of strings' when given a truthy moves argument that is not a list. The check is `if moves and not isinstance(moves, list)`, so an empty array passes and a tuple is rejected. ```python try: await bridge.mcp.call_tool("set_position", {"moves": "e2e4"}) except ValueError as e: assert str(e) == "Moves must be a list of strings" ``` -------------------------------- ### OptionMetadata TypedDict class definition Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/types.md Defines metadata for a single UCI engine option, mirroring esca.uci.Option fields. The 'type' field accepts one of 'check', 'spin', 'combo', 'button', 'string'. 'min' and 'max' only apply to 'spin' type, while 'var' only applies to 'combo' type. ```python class OptionMetadata(TypedDict): """Metadata for a single UCI engine option.""" name: str type: str # 'check', 'spin', 'combo', 'button', 'string' default: ConfigValue min: int | None # Only for 'spin' type max: int | None # Only for 'spin' type var: list[str] | None # Only for 'combo' type ``` -------------------------------- ### set_position Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/endpoints.md Sets the current chess position, optionally from a FEN string and a list of moves in UCI format. ```APIDOC ## set_position ### Description Sets the current chess position, optionally from a FEN string and a list of moves in UCI format. ### Input - `fen` (string | null) - Optional - FEN to start from; null/absent means the starting position. - `moves` (array | null) - Optional - Moves in UCI format replayed from that position; stored for the next `get_best_move` only. ### Output - `success` (boolean) - Always `true` on success. ### Errors - `ValueError` - "Invalid FEN string: {fen}" - `ValueError` - "Moves must be a list of strings" when `moves` is truthy but not a JSON array. - `RuntimeError` - If the engine cannot be started. ``` -------------------------------- ### stop method signature Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/engine.md Signature of the stop method. Sends quit to the engine and releases the handle. Errors during shutdown are logged but not raised. ```python async def stop(self) -> None: ``` -------------------------------- ### EngineId TypedDict Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/types.md TypedDict for engine identification reported by the UCI engine during the handshake. total=False allows either key to be absent; UCIEngine.get_engine_id omits keys whose engine-reported value is None. Returned by UCIEngine.get_engine_id and contained in EngineInfo.id. ```python class EngineId(TypedDict, total=False): """ Engine identification from UCI protocol. Uses total=False since different engines may return different keys. Common keys are 'name' and 'author', but engines may include others. """ name: str author: str ``` -------------------------------- ### Catch ValueError for invalid FEN string Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/errors.md Use this snippet to verify that the MCP tool 'analyze' raises a ValueError with the exact message 'Invalid FEN string: not a fen' when given an invalid FEN. The validation parses the position but does not check move legality; UCIEngine may still raise ValueError from esca.Game.from_fen or game.play(move) when a stored FEN or a move in moves cannot be read. ```python try: await bridge.mcp.call_tool("analyze", {"fen": "not a fen"}) except Exception as e: assert str(e) == "Invalid FEN string: not a fen" ``` -------------------------------- ### ConfigValue type alias Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/types.md Defines the set of types a UCI option value can take. Used by OptionMetadata.default, OptionInfo.current_value, EngineInfo.configured_options, SetEngineOptionsResult.applied_options, and as parameter/value types of UCIEngine.set_options and UCIEngine.get_current_option_values. ```python ConfigValue = str | int | bool | None ``` -------------------------------- ### get_engine_id Source: https://github.com/anglerfishchess/chess-uci-mcp/blob/main/_autodocs/api-reference/engine.md Returns the engine identification reported during the UCI handshake. ```APIDOC ## get_engine_id ### Description Returns the engine identification reported during the UCI handshake. ### Method N/A (Python method) ### Endpoint N/A (Python method) ### Parameters None ### Returns `EngineId` — see [types.md](../types.md). A `dict` (TypedDict, `total=False`) that may contain `"name"` and/or `"author"` (`str`); keys with `None` values are omitted. Most engines report at least a `name`. ### Throws | Error | Condition | |-------|-----------| | `RuntimeError("Engine not started")` | Engine not started. | ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.