chess-esca-mcp 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,146 @@
1
+ Metadata-Version: 2.4
2
+ Name: chess-esca-mcp
3
+ Version: 0.4.0
4
+ Summary: An MCP server over the esca chess library: rules, facts, explanations, openings and PGN, with no engine
5
+ Author-email: Alexander Myodov <amyodov@gmail.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/AnglerfishChess/esca
8
+ Project-URL: Repository, https://github.com/AnglerfishChess/esca
9
+ Project-URL: Documentation, https://github.com/AnglerfishChess/esca/blob/main/mcp/README.md
10
+ Project-URL: Changelog, https://github.com/AnglerfishChess/esca/blob/main/CHANGELOG.md
11
+ Project-URL: Issues, https://github.com/AnglerfishChess/esca/issues
12
+ Keywords: chess,chess960,fen,pgn,MCP,model context protocol,esca
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Games/Entertainment :: Board Games
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Requires-Python: >=3.12
23
+ Description-Content-Type: text/markdown
24
+ Requires-Dist: esca==0.4.0
25
+ Requires-Dist: mcp<2.0.0,>=1.28.1
26
+
27
+ # chess-esca-mcp
28
+
29
+ An MCP server over [esca](https://github.com/AnglerfishChess/esca): the rules of chess as JSON an
30
+ agent can read.
31
+
32
+ <!-- mcp-name: io.github.AnglerfishChess/chess-esca-mcp -->
33
+
34
+ FEN and moves go in; enums and the squares behind them come out. Whether a move is legal and why
35
+ not, what a position's status is and what either side may claim, the named facts of the position,
36
+ the ending the material makes and what theory says it is, the opening's ECO code, the moves an
37
+ opening book holds, and PGN read and written. Every categorical answer also carries `prose`: the
38
+ same thing in one plain English sentence, beside the enum rather than instead of it.
39
+
40
+ **There is no engine here and no search.** Nothing this server answers says how *good* a move is.
41
+ For a number and a line, use [chess-uci-mcp](https://github.com/AnglerfishChess/chess-uci-mcp),
42
+ which drives Stockfish or Leela; the two answer different questions and sit well side by side.
43
+
44
+ ## Dependencies
45
+
46
+ Python 3.12 or newer, and `uv`/`uvx`.
47
+
48
+ ## Usage
49
+
50
+ ```json
51
+ "mcpServers": {
52
+ "chess-esca-mcp": {
53
+ "command": "uvx",
54
+ "args": ["chess-esca-mcp@latest"]
55
+ }
56
+ }
57
+ ```
58
+
59
+ For Claude Desktop that is `claude_desktop_config.json`, under **Settings** → **Developer** →
60
+ **Edit Config**:
61
+
62
+ * macOS: `~/Library/Application\ Support/Claude/claude_desktop_config.json`
63
+ * Windows: `%APPDATA%/Claude/claude_desktop_config.json`
64
+ * Linux: `~/.config/Claude/claude_desktop_config.json`
65
+
66
+ For Claude Code, the plugin does the wiring:
67
+
68
+ ```
69
+ /plugin marketplace add AnglerfishChess/plugins
70
+ /plugin install chess-esca-mcp@anglerfish-chess
71
+ ```
72
+
73
+ The server takes no arguments. It reads nothing but the position you hand it and, for
74
+ `book_moves`, the book file you name.
75
+
76
+ ## Tools
77
+
78
+ Every tool takes the position the same way: `fen` (the start position when omitted), `moves`
79
+ played from it — each written as SAN (`Nf3`) or as UCI (`g1f3`) — or a whole game as `pgn`
80
+ instead. `variant` is `classic` or `chess960`. Repetition and fifty-move claims are only visible
81
+ when the moves that led to the position are given, since a FEN does not carry them.
82
+
83
+ | Tool | Answers |
84
+ |---|---|
85
+ | `position` | The whole state: side to move, check and its checkers, game status, automatic and claimable draws with their evidence, legal-move count, opening, material, both castlings of both colours with every obstacle, the en-passant offer, pins and skewers, and the ending where the material makes one. |
86
+ | `legal_moves` | Every legal move in SAN and UCI, each with its role, victim, promotion, check and static exchange, and grouped as captures, checks, castling, promotions, en passant and quiet. |
87
+ | `explain_move` | Whether one move is legal. If not, every reason at once, each with the squares it was read off. If so, what it changes, the position after it, and the draws it would open. |
88
+ | `facts` | The named facts of the position, group by group, every value labelled by name and, where it differs between the sides, by colour. `groups` selects; `placement` and `maps` are left out unless asked for. |
89
+ | `ending` | The ending the material makes: its signature, its class, what theory says the result is, the technique that gets it, and the pawn race, bishops and opposition it was read off. |
90
+ | `opening` | The ECO code and name of the position, and the deepest named position the line reached. |
91
+ | `book_moves` | The moves a Polyglot opening book holds for the position, with their weights. |
92
+ | `pgn` | A PGN game read into headers, moves, comments, final position, opening and result. |
93
+ | `to_pgn` | A list of moves written out as a PGN game. |
94
+
95
+ An input that names no position, no move or no game comes back as
96
+ `{"error": {"kind": ..., "message": ..., "hint": ...}}` — never a traceback.
97
+
98
+ One resource, `esca://facts-catalogue`, lists every fact group and every field it holds, with the
99
+ type each carries and one sentence of what it means; esca generates it from the fact definitions
100
+ themselves. One prompt, `analyse-position`, walks an agent through reading a position with
101
+ these tools.
102
+
103
+ ### Opening books
104
+
105
+ No book is bundled. `book_moves` takes the path to a Polyglot `.bin` file of your own; the format
106
+ is the common one, so a book written for any engine that reads Polyglot works. `esca.polyglot`
107
+ has `download(url, path)` for fetching one, and a `Builder` that writes a book from PGN.
108
+
109
+ ## Development
110
+
111
+ The server is a second distribution inside the esca repository: the library at the root, this
112
+ directory beside it. It takes esca from the crate next door while you work on it, and from PyPI
113
+ once installed.
114
+
115
+ ```bash
116
+ git clone https://github.com/AnglerfishChess/esca.git
117
+ cd esca/mcp
118
+
119
+ uv sync --all-groups # builds the esca extension from ../ and installs it here
120
+ uv run --no-sync pytest
121
+ uvx ruff check . && uvx ruff format --check . && uvx pyrefly check
122
+ ```
123
+
124
+ Run it from the checkout with `uv run chess-esca-mcp`.
125
+
126
+ The version is esca's own: one tag releases the library and this server together, and the
127
+ `esca==` pin names that same version.
128
+
129
+ ### The MCP registry
130
+
131
+ [registry.modelcontextprotocol.io](https://registry.modelcontextprotocol.io) is the index of
132
+ public MCP servers. The listing is described by `server.json`, under the name
133
+ `io.github.AnglerfishChess/chess-esca-mcp`; ownership of the PyPI package is proven by the
134
+ `mcp-name:` marker near the top of this file, which becomes the package description PyPI serves.
135
+ The registry reads it from the *published* artifact, so it counts only once a release carrying it
136
+ reaches PyPI.
137
+
138
+ ## Related projects
139
+
140
+ * [esca](https://github.com/AnglerfishChess/esca) — the library this serves.
141
+ * [chess-uci-mcp](https://github.com/AnglerfishChess/chess-uci-mcp) — the engine side: analysis
142
+ and best moves from Stockfish or Leela.
143
+
144
+ ## License
145
+
146
+ MIT — see [LICENSE](https://github.com/AnglerfishChess/esca/blob/main/LICENSE).
@@ -0,0 +1,120 @@
1
+ # chess-esca-mcp
2
+
3
+ An MCP server over [esca](https://github.com/AnglerfishChess/esca): the rules of chess as JSON an
4
+ agent can read.
5
+
6
+ <!-- mcp-name: io.github.AnglerfishChess/chess-esca-mcp -->
7
+
8
+ FEN and moves go in; enums and the squares behind them come out. Whether a move is legal and why
9
+ not, what a position's status is and what either side may claim, the named facts of the position,
10
+ the ending the material makes and what theory says it is, the opening's ECO code, the moves an
11
+ opening book holds, and PGN read and written. Every categorical answer also carries `prose`: the
12
+ same thing in one plain English sentence, beside the enum rather than instead of it.
13
+
14
+ **There is no engine here and no search.** Nothing this server answers says how *good* a move is.
15
+ For a number and a line, use [chess-uci-mcp](https://github.com/AnglerfishChess/chess-uci-mcp),
16
+ which drives Stockfish or Leela; the two answer different questions and sit well side by side.
17
+
18
+ ## Dependencies
19
+
20
+ Python 3.12 or newer, and `uv`/`uvx`.
21
+
22
+ ## Usage
23
+
24
+ ```json
25
+ "mcpServers": {
26
+ "chess-esca-mcp": {
27
+ "command": "uvx",
28
+ "args": ["chess-esca-mcp@latest"]
29
+ }
30
+ }
31
+ ```
32
+
33
+ For Claude Desktop that is `claude_desktop_config.json`, under **Settings** → **Developer** →
34
+ **Edit Config**:
35
+
36
+ * macOS: `~/Library/Application\ Support/Claude/claude_desktop_config.json`
37
+ * Windows: `%APPDATA%/Claude/claude_desktop_config.json`
38
+ * Linux: `~/.config/Claude/claude_desktop_config.json`
39
+
40
+ For Claude Code, the plugin does the wiring:
41
+
42
+ ```
43
+ /plugin marketplace add AnglerfishChess/plugins
44
+ /plugin install chess-esca-mcp@anglerfish-chess
45
+ ```
46
+
47
+ The server takes no arguments. It reads nothing but the position you hand it and, for
48
+ `book_moves`, the book file you name.
49
+
50
+ ## Tools
51
+
52
+ Every tool takes the position the same way: `fen` (the start position when omitted), `moves`
53
+ played from it — each written as SAN (`Nf3`) or as UCI (`g1f3`) — or a whole game as `pgn`
54
+ instead. `variant` is `classic` or `chess960`. Repetition and fifty-move claims are only visible
55
+ when the moves that led to the position are given, since a FEN does not carry them.
56
+
57
+ | Tool | Answers |
58
+ |---|---|
59
+ | `position` | The whole state: side to move, check and its checkers, game status, automatic and claimable draws with their evidence, legal-move count, opening, material, both castlings of both colours with every obstacle, the en-passant offer, pins and skewers, and the ending where the material makes one. |
60
+ | `legal_moves` | Every legal move in SAN and UCI, each with its role, victim, promotion, check and static exchange, and grouped as captures, checks, castling, promotions, en passant and quiet. |
61
+ | `explain_move` | Whether one move is legal. If not, every reason at once, each with the squares it was read off. If so, what it changes, the position after it, and the draws it would open. |
62
+ | `facts` | The named facts of the position, group by group, every value labelled by name and, where it differs between the sides, by colour. `groups` selects; `placement` and `maps` are left out unless asked for. |
63
+ | `ending` | The ending the material makes: its signature, its class, what theory says the result is, the technique that gets it, and the pawn race, bishops and opposition it was read off. |
64
+ | `opening` | The ECO code and name of the position, and the deepest named position the line reached. |
65
+ | `book_moves` | The moves a Polyglot opening book holds for the position, with their weights. |
66
+ | `pgn` | A PGN game read into headers, moves, comments, final position, opening and result. |
67
+ | `to_pgn` | A list of moves written out as a PGN game. |
68
+
69
+ An input that names no position, no move or no game comes back as
70
+ `{"error": {"kind": ..., "message": ..., "hint": ...}}` — never a traceback.
71
+
72
+ One resource, `esca://facts-catalogue`, lists every fact group and every field it holds, with the
73
+ type each carries and one sentence of what it means; esca generates it from the fact definitions
74
+ themselves. One prompt, `analyse-position`, walks an agent through reading a position with
75
+ these tools.
76
+
77
+ ### Opening books
78
+
79
+ No book is bundled. `book_moves` takes the path to a Polyglot `.bin` file of your own; the format
80
+ is the common one, so a book written for any engine that reads Polyglot works. `esca.polyglot`
81
+ has `download(url, path)` for fetching one, and a `Builder` that writes a book from PGN.
82
+
83
+ ## Development
84
+
85
+ The server is a second distribution inside the esca repository: the library at the root, this
86
+ directory beside it. It takes esca from the crate next door while you work on it, and from PyPI
87
+ once installed.
88
+
89
+ ```bash
90
+ git clone https://github.com/AnglerfishChess/esca.git
91
+ cd esca/mcp
92
+
93
+ uv sync --all-groups # builds the esca extension from ../ and installs it here
94
+ uv run --no-sync pytest
95
+ uvx ruff check . && uvx ruff format --check . && uvx pyrefly check
96
+ ```
97
+
98
+ Run it from the checkout with `uv run chess-esca-mcp`.
99
+
100
+ The version is esca's own: one tag releases the library and this server together, and the
101
+ `esca==` pin names that same version.
102
+
103
+ ### The MCP registry
104
+
105
+ [registry.modelcontextprotocol.io](https://registry.modelcontextprotocol.io) is the index of
106
+ public MCP servers. The listing is described by `server.json`, under the name
107
+ `io.github.AnglerfishChess/chess-esca-mcp`; ownership of the PyPI package is proven by the
108
+ `mcp-name:` marker near the top of this file, which becomes the package description PyPI serves.
109
+ The registry reads it from the *published* artifact, so it counts only once a release carrying it
110
+ reaches PyPI.
111
+
112
+ ## Related projects
113
+
114
+ * [esca](https://github.com/AnglerfishChess/esca) — the library this serves.
115
+ * [chess-uci-mcp](https://github.com/AnglerfishChess/chess-uci-mcp) — the engine side: analysis
116
+ and best moves from Stockfish or Leela.
117
+
118
+ ## License
119
+
120
+ MIT — see [LICENSE](https://github.com/AnglerfishChess/esca/blob/main/LICENSE).
@@ -0,0 +1,9 @@
1
+ """An MCP server over the esca chess library.
2
+
3
+ Rules, explanations, facts, openings, opening books and PGN, as JSON an agent
4
+ can read: FEN and moves in, enums and the squares behind them out. No engine
5
+ and no search — nothing here says how good a move is.
6
+ """
7
+
8
+ #: The esca release this server serves; the two are versioned together.
9
+ __version__ = "0.4.0"
@@ -0,0 +1,31 @@
1
+ """The command line: `chess-esca-mcp` serves the tools over stdio."""
2
+
3
+ import argparse
4
+ import logging
5
+ import sys
6
+
7
+ from chess_esca_mcp import __version__
8
+ from chess_esca_mcp.server import run
9
+
10
+
11
+ def main() -> None:
12
+ """Parses the arguments and serves until the client closes stdin."""
13
+ parser = argparse.ArgumentParser(
14
+ prog="chess-esca-mcp",
15
+ description="An MCP server over the esca chess library: rules, facts and explanations.",
16
+ )
17
+ parser.add_argument("--version", action="version", version=f"chess-esca-mcp {__version__}")
18
+ parser.add_argument("--debug", action="store_true", help="Log at debug level, to stderr.")
19
+ arguments = parser.parse_args()
20
+
21
+ # stdout carries the protocol; every line of ours goes to stderr.
22
+ logging.basicConfig(
23
+ level=logging.DEBUG if arguments.debug else logging.INFO,
24
+ format="%(asctime)s %(name)s %(levelname)s %(message)s",
25
+ stream=sys.stderr,
26
+ )
27
+ run()
28
+
29
+
30
+ if __name__ == "__main__":
31
+ main()
@@ -0,0 +1,99 @@
1
+ """The named facts of a position, group by group.
2
+
3
+ A group is served in the one JSON form esca writes everywhere — `{field:
4
+ value}`, a per-side value `{"white": …, "black": …}`, a set of squares the list
5
+ of its square names in board order, a set of files the list of its letters —
6
+ so what this tool answers and what `docs/facts.schema.json` describes are the
7
+ same thing.
8
+
9
+ Where a value is a run of positions, `field_notes` carries that field's
10
+ catalogue meaning once, since the meaning is what says which end is which.
11
+ """
12
+
13
+ from typing import Any, cast
14
+
15
+ import esca
16
+
17
+ from chess_esca_mcp.rendering import prose
18
+
19
+ #: Every group `docs/features.md` defines, in the order `Facts` declares them.
20
+ GROUPS: tuple[str, ...] = tuple(esca.Facts.groups())
21
+
22
+ #: What `groups` answers when a caller names none: `placement` restates the
23
+ #: board the FEN already gives, and `maps` restates the attacks and threats.
24
+ DEFAULT_GROUPS: tuple[str, ...] = tuple(name for name in GROUPS if name not in ("placement", "maps"))
25
+
26
+
27
+ def _is_run(declared: str) -> bool:
28
+ """Whether the declared type is a run of positions rather than one value."""
29
+ return "PerFile<" in declared or "PerRank<" in declared or "[" in declared
30
+
31
+
32
+ #: The catalogue meaning of every fact whose value is a run of positions,
33
+ #: keyed `group.field`. A reader of `[1, 1, 1, 1, 1, 1, 1, 1]` needs it.
34
+ RUN_NOTES: dict[str, str] = {
35
+ f"{group['name']}.{field['name']}": field["meaning"]
36
+ for group in esca.facts_catalogue()
37
+ for field in group["fields"]
38
+ if _is_run(field["type"])
39
+ }
40
+
41
+
42
+ def group_facts(facts: esca.Facts, name: str) -> dict[str, Any]:
43
+ """Every fact of one group, by name, as plain data."""
44
+ return cast("dict[str, Any]", facts.group(name).to_dict())
45
+
46
+
47
+ def unknown_groups(names: list[str]) -> list[str]:
48
+ """The names among `names` that no group answers to."""
49
+ return [name for name in names if name not in GROUPS]
50
+
51
+
52
+ def run_notes(names: list[str]) -> dict[str, str]:
53
+ """What the positions of every run the named groups carry mean."""
54
+ wanted = set(names)
55
+ return {key: note for key, note in RUN_NOTES.items() if key.split(".")[0] in wanted}
56
+
57
+
58
+ def facts_content(facts: esca.Facts, names: list[str] | None) -> dict[str, Any]:
59
+ """The named groups of `facts`, and what else could have been asked for."""
60
+ wanted = list(DEFAULT_GROUPS) if not names else [name for name in GROUPS if name in set(names)]
61
+ return {
62
+ "side_to_move": facts.side_to_move,
63
+ "groups": {name: group_facts(facts, name) for name in wanted},
64
+ "field_notes": run_notes(wanted),
65
+ "groups_available": list(GROUPS),
66
+ "prose": prose(facts),
67
+ }
68
+
69
+
70
+ def catalogue() -> dict[str, Any]:
71
+ """Every group, field, type and meaning, as the resource serves it."""
72
+ return {
73
+ "groups": [
74
+ {
75
+ "name": group["name"],
76
+ "meaning": group["meaning"],
77
+ "fields": [
78
+ {"name": field["name"], "type": field["type"], "meaning": field["meaning"]}
79
+ for field in group["fields"]
80
+ ],
81
+ }
82
+ for group in esca.facts_catalogue()
83
+ ],
84
+ "move": [
85
+ {"name": field["name"], "type": field["type"], "meaning": field["meaning"]}
86
+ for field in esca.move_facts_catalogue()
87
+ ],
88
+ "types": {
89
+ "ByColour": 'one value per colour, written {"white": …, "black": …}',
90
+ "SquareSet": (
91
+ "a set of squares, written as a list of square names in board order: a1, b1 through h1, then a2"
92
+ ),
93
+ "FileSet": "a set of files, written as a list of file letters, file a first",
94
+ "PerFile": "eight values, file a first, through file h",
95
+ "PerRank": "eight values, rank 1 first, through rank 8",
96
+ "[T; n]": "n values, in the order the fact's own meaning states",
97
+ "Option": "a value that may be absent, written null when it is",
98
+ },
99
+ }
@@ -0,0 +1,169 @@
1
+ """Reading a position out of what a caller supplied, and saying what is wrong
2
+ with it when nothing can be read.
3
+
4
+ Every failure is a `ChessInputError`, which carries a `kind`, a sentence and
5
+ the evidence a caller needs to fix the call — never a traceback.
6
+ """
7
+
8
+ from typing import Any
9
+
10
+ import esca
11
+
12
+ #: The variants a caller may name. esca calls classic chess `chess`; both
13
+ #: spellings are accepted and `classic` is the one the answers use.
14
+ VARIANTS = {"classic": esca.CLASSIC, "chess": esca.CLASSIC, "chess960": esca.CHESS960}
15
+
16
+
17
+ class ChessInputError(Exception):
18
+ """An input that names no position, no move or no game."""
19
+
20
+ def __init__(self, kind: str, message: str, hint: str | None = None, **evidence: Any) -> None:
21
+ super().__init__(message)
22
+ self.kind = kind
23
+ self.message = message
24
+ self.hint = hint
25
+ self.evidence = evidence
26
+
27
+ def content(self) -> dict[str, Any]:
28
+ """The error as a tool answers it."""
29
+ error: dict[str, Any] = {"kind": self.kind, "message": self.message}
30
+ if self.hint is not None:
31
+ error["hint"] = self.hint
32
+ error.update(self.evidence)
33
+ return {"error": error}
34
+
35
+
36
+ def variant_named(name: str) -> esca.Variant:
37
+ """The rules `name` selects."""
38
+ if name not in VARIANTS:
39
+ raise ChessInputError(
40
+ "unknown_variant",
41
+ f"{name!r} is not a variant this server knows",
42
+ hint=f"use one of: {', '.join(sorted(VARIANTS))}",
43
+ )
44
+ return VARIANTS[name]
45
+
46
+
47
+ def variant_label(variant: esca.Variant) -> str:
48
+ """The name the answers give `variant`."""
49
+ return "chess960" if variant == esca.CHESS960 else "classic"
50
+
51
+
52
+ def play(game: esca.Game, text: str, index: int) -> None:
53
+ """Plays one move written as SAN or as UCI.
54
+
55
+ `index` is the move's place in the sequence, for the error to name.
56
+ """
57
+ for attempt in (game.play_san, game.play):
58
+ try:
59
+ attempt(text)
60
+ except ValueError:
61
+ continue
62
+ return
63
+ raise ChessInputError(
64
+ "illegal_move",
65
+ f"{text!r} names no legal move in {game.position.fen}",
66
+ hint="moves are SAN ('Nf3', 'exd6') or UCI ('g1f3', 'e5d6'); see legal_moves for what is playable",
67
+ move=text,
68
+ move_index=index,
69
+ fen=game.position.fen,
70
+ legal_moves=sorted(game.move_to_san(mv) for mv in game.legal_moves()),
71
+ )
72
+
73
+
74
+ def read_game(
75
+ fen: str | None = None,
76
+ moves: list[str] | None = None,
77
+ pgn: str | None = None,
78
+ variant: str = "classic",
79
+ ) -> esca.Game:
80
+ """The game `fen`, `moves` and `pgn` describe between them.
81
+
82
+ `pgn` stands alone and brings its own rules and start position. Otherwise
83
+ the game starts at `fen`, or at the variant's own start position, and
84
+ `moves` are played from there in order, each written as SAN or as UCI.
85
+ """
86
+ if pgn is not None:
87
+ if fen is not None or moves:
88
+ raise ChessInputError(
89
+ "conflicting_inputs",
90
+ "pgn carries its own start position and moves",
91
+ hint="pass pgn on its own, or pass fen and moves instead",
92
+ )
93
+ try:
94
+ return read_pgn(pgn).game()
95
+ except ValueError as error:
96
+ raise ChessInputError(
97
+ "unplayable_pgn",
98
+ f"the movetext does not play out: {error}",
99
+ hint="every move must be legal in the position it is written for",
100
+ ) from None
101
+
102
+ rules = variant_named(variant)
103
+ if fen is None:
104
+ game = esca.Game(variant=rules)
105
+ else:
106
+ try:
107
+ game = esca.Game.from_fen(fen, variant=rules)
108
+ except ValueError as error:
109
+ raise ChessInputError(
110
+ "invalid_fen",
111
+ f"{fen!r} is not a position under {variant} rules: {error}",
112
+ hint=(
113
+ "a FEN is six fields: placement, side to move, castling rights, en-passant "
114
+ "target, halfmove clock, fullmove number"
115
+ ),
116
+ fen=fen,
117
+ ) from None
118
+ for index, text in enumerate(moves or []):
119
+ play(game, text, index)
120
+ return game
121
+
122
+
123
+ def pgn_games(text: str) -> list[esca.pgn.Game]:
124
+ """Every game a PGN source holds."""
125
+ try:
126
+ return list(esca.pgn.read_string(text))
127
+ except ValueError as error:
128
+ raise ChessInputError(
129
+ "invalid_pgn",
130
+ f"the PGN could not be read: {error}",
131
+ hint="tag pairs in brackets, a blank line, then the movetext",
132
+ ) from None
133
+
134
+
135
+ def read_pgn(text: str, index: int = 0) -> esca.pgn.Game:
136
+ """The game at `index` of a PGN source."""
137
+ games = pgn_games(text)
138
+ if not games:
139
+ raise ChessInputError(
140
+ "empty_pgn",
141
+ "the PGN holds no game",
142
+ hint="a game is a tag section and a movetext section",
143
+ )
144
+ if not 0 <= index < len(games):
145
+ raise ChessInputError(
146
+ "no_such_game",
147
+ f"the PGN holds {len(games)} game(s), so there is no game {index}",
148
+ hint=f"index is zero-based: 0 to {len(games) - 1}",
149
+ games_in_source=len(games),
150
+ )
151
+ return games[index]
152
+
153
+
154
+ def parse_move(game: esca.Game, text: str) -> esca.Move | None:
155
+ """The legal move `text` names, or `None` when it names none."""
156
+ position = game.position
157
+ for legal in game.legal_moves():
158
+ if text == game.move_to_san(legal) or text == game.move_to_uci(legal):
159
+ return legal
160
+ # SAN written without its check or mate suffix, and UCI in either castling
161
+ # spelling, both go through the variant's own reader.
162
+ scratch = esca.Game.from_position(position, variant=game.variant)
163
+ for attempt in (scratch.play_san, scratch.play):
164
+ try:
165
+ attempt(text)
166
+ except ValueError:
167
+ continue
168
+ return scratch.moves[-1]
169
+ return None