From 4f096953d796b378ebdfbc72563e4df50adea226 Mon Sep 17 00:00:00 2001 From: ai-chess Date: Thu, 14 May 2026 23:16:24 +0300 Subject: [PATCH] feat(mcp): per-side tool builders (get_board, move, resign, draw) --- src/ai_chess/mcp_server.py | 183 +++++++++++++++++++++++++++++++++++++ tests/test_mcp_server.py | 91 ++++++++++++++++++ 2 files changed, 274 insertions(+) create mode 100644 src/ai_chess/mcp_server.py create mode 100644 tests/test_mcp_server.py diff --git a/src/ai_chess/mcp_server.py b/src/ai_chess/mcp_server.py new file mode 100644 index 0000000..0927764 --- /dev/null +++ b/src/ai_chess/mcp_server.py @@ -0,0 +1,183 @@ +from __future__ import annotations + +from typing import Any, Awaitable, Callable + +from ai_chess.sides import Side +from ai_chess.state import AppState + + +Tool = Callable[[dict[str, Any]], Awaitable[dict[str, Any]]] + + +def build_tools_for_side(side: Side, state: AppState) -> dict[str, Tool]: + async def _publish(event_type: str, **payload: Any) -> None: + await state.events.publish({"type": event_type, **payload}) + + async def get_board(_args: dict[str, Any]) -> dict[str, Any]: + g = state.game + if g is None: + return {"error": "no_active_game"} + st = g.get_state() + return { + "fen": st["fen"], + "ascii": st["ascii"], + "side_to_move": st["side_to_move"], + "status": st["status"], + } + + async def get_history(_args: dict[str, Any]) -> dict[str, Any]: + g = state.game + if g is None: + return {"error": "no_active_game"} + return {"history": [h.to_dict() for h in g.history]} + + async def status(_args: dict[str, Any]) -> dict[str, Any]: + g = state.game + if g is None: + return {"error": "no_active_game"} + return g.get_state()["status"] + + async def move(args: dict[str, Any]) -> dict[str, Any]: + g = state.game + if g is None: + return {"ok": False, "reason": "no_active_game"} + mv = str(args.get("move", "")).strip() + if not mv: + return {"ok": False, "reason": "missing_move"} + comment = args.get("comment") + if comment is not None: + comment = str(comment) + result = g.try_move(side, mv, comment=comment, + allow_illegal=state.settings.allow_illegal_moves) + payload = result.to_dict() + if result.ok: + await _publish( + "move", + side=side.value, + san=result.san, + uci=result.uci, + comment=comment, + fen=result.fen, + ascii=result.ascii, + illegal=result.illegal, + status=result.status, + history=result.history, + ) + if g.is_game_over(): + await _publish( + "game_over", + result=g.result, + termination=g.termination, + ) + return payload + + async def resign(args: dict[str, Any]) -> dict[str, Any]: + if not state.settings.allow_draw_resign: + return {"ok": False, "reason": "resign_disabled"} + g = state.game + if g is None: + return {"ok": False, "reason": "no_active_game"} + out = g.resign(side, comment=args.get("comment")) + if out.get("ok"): + await _publish("resign", side=side.value, comment=args.get("comment")) + await _publish("game_over", result=g.result, termination=g.termination) + return out + + async def offer_draw(args: dict[str, Any]) -> dict[str, Any]: + if not state.settings.allow_draw_resign: + return {"ok": False, "reason": "draw_disabled"} + g = state.game + if g is None: + return {"ok": False, "reason": "no_active_game"} + out = g.offer_draw(side, comment=args.get("comment")) + if out.get("ok"): + if g.is_game_over(): + await _publish("game_over", result=g.result, termination=g.termination) + else: + await _publish("draw_offered", side=side.value, comment=args.get("comment")) + return out + + async def accept_draw(args: dict[str, Any]) -> dict[str, Any]: + if not state.settings.allow_draw_resign: + return {"ok": False, "reason": "draw_disabled"} + g = state.game + if g is None: + return {"ok": False, "reason": "no_active_game"} + out = g.accept_draw(side) + if out.get("ok"): + await _publish("game_over", result=g.result, termination=g.termination) + return out + + async def decline_draw(_args: dict[str, Any]) -> dict[str, Any]: + if not state.settings.allow_draw_resign: + return {"ok": False, "reason": "draw_disabled"} + g = state.game + if g is None: + return {"ok": False, "reason": "no_active_game"} + out = g.decline_draw(side) + if out.get("ok"): + await state.events.publish({"type": "draw_declined", "side": side.value}) + return out + + return { + "get_board": get_board, + "get_history": get_history, + "status": status, + "move": move, + "resign": resign, + "offer_draw": offer_draw, + "accept_draw": accept_draw, + "decline_draw": decline_draw, + } + + +# JSON schema fragments for tool advertising in MCP +TOOL_SCHEMAS: dict[str, dict[str, Any]] = { + "get_board": { + "description": "Получить текущую позицию (ASCII доска, FEN, чей ход, статус).", + "inputSchema": {"type": "object", "properties": {}}, + }, + "get_history": { + "description": "Получить список ходов с комментариями обеих сторон.", + "inputSchema": {"type": "object", "properties": {}}, + }, + "status": { + "description": "Статус партии (результат, шахи, счётчики).", + "inputSchema": {"type": "object", "properties": {}}, + }, + "move": { + "description": "Сделать ход. Поле comment передаётся сопернику вместе с уведомлением.", + "inputSchema": { + "type": "object", + "properties": { + "move": {"type": "string", + "description": "UCI (e2e4) или SAN (e4, Nf3, O-O)."}, + "comment": {"type": "string", + "description": "Реплика сопернику (1–3 предложения)."}, + }, + "required": ["move"], + }, + }, + "resign": { + "description": "Сдаться (если разрешено настройками).", + "inputSchema": { + "type": "object", + "properties": {"comment": {"type": "string"}}, + }, + }, + "offer_draw": { + "description": "Предложить ничью (если разрешено настройками).", + "inputSchema": { + "type": "object", + "properties": {"comment": {"type": "string"}}, + }, + }, + "accept_draw": { + "description": "Принять оффер ничьи противника.", + "inputSchema": {"type": "object", "properties": {}}, + }, + "decline_draw": { + "description": "Отклонить оффер ничьи противника.", + "inputSchema": {"type": "object", "properties": {}}, + }, +} diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py new file mode 100644 index 0000000..55af7f2 --- /dev/null +++ b/tests/test_mcp_server.py @@ -0,0 +1,91 @@ +import pytest + +from ai_chess.chess_game import ChessGame +from ai_chess.mcp_server import build_tools_for_side +from ai_chess.settings import Settings +from ai_chess.sides import Side +from ai_chess.state import AppState + + +def fresh_state() -> AppState: + s = AppState() + s.game = ChessGame(game_id="t1") + return s + + +@pytest.mark.asyncio +async def test_get_board(): + s = fresh_state() + tools = build_tools_for_side(Side.WHITE, s) + res = await tools["get_board"]({}) + assert "ascii" in res and "fen" in res + assert res["side_to_move"] == "white" + + +@pytest.mark.asyncio +async def test_move_legal(): + s = fresh_state() + tools = build_tools_for_side(Side.WHITE, s) + res = await tools["move"]({"move": "e4", "comment": "го"}) + assert res["ok"] is True + assert res["san"] == "e4" + + +@pytest.mark.asyncio +async def test_move_not_your_turn(): + s = fresh_state() + tools = build_tools_for_side(Side.BLACK, s) + res = await tools["move"]({"move": "e5"}) + assert res["ok"] is False + assert res["reason"] == "not_your_turn" + + +@pytest.mark.asyncio +async def test_move_illegal_default_off(): + s = fresh_state() + tools = build_tools_for_side(Side.WHITE, s) + res = await tools["move"]({"move": "e2e7"}) + assert res["ok"] is False + assert res["reason"] == "illegal_move" + + +@pytest.mark.asyncio +async def test_move_illegal_allowed_when_flag_on(): + s = fresh_state() + s.settings = Settings(allow_illegal_moves=True) + tools = build_tools_for_side(Side.WHITE, s) + res = await tools["move"]({"move": "e2e7"}) + assert res["ok"] is True + assert res["illegal"] is True + + +@pytest.mark.asyncio +async def test_resign_disabled(): + s = fresh_state() + s.settings = Settings(allow_draw_resign=False) + tools = build_tools_for_side(Side.WHITE, s) + res = await tools["resign"]({}) + assert res["ok"] is False + assert res["reason"] == "resign_disabled" + + +@pytest.mark.asyncio +async def test_resign_ok_then_game_over(): + s = fresh_state() + tools = build_tools_for_side(Side.WHITE, s) + res = await tools["resign"]({"comment": "сдаюсь"}) + assert res["ok"] is True + assert s.game.result == "0-1" + + +@pytest.mark.asyncio +async def test_draw_offer_and_accept(): + s = fresh_state() + s.game.try_move(Side.WHITE, "e4") + tools_b = build_tools_for_side(Side.BLACK, s) + r1 = await tools_b["offer_draw"]({"comment": "ничья?"}) + assert r1["ok"] is True + tools_w = build_tools_for_side(Side.WHITE, s) + r2 = await tools_w["accept_draw"]({}) + assert r2["ok"] is True + assert s.game.result == "1/2-1/2"