feat(app): FastAPI REST + WS + MCP HTTP transport

Implements build_app() with REST endpoints (/api/state, /api/games,
/api/settings, /api/new-game, /api/agent-binding), WebSocket /ws for
realtime events, and custom JSON-RPC MCP transport at /mcp/{side}
supporting initialize, tools/list, and tools/call with proper
content-wrapping and isError flag. Static UI mount guarded by
PUBLIC_DIR existence check. All 5 e2e tests pass.
This commit is contained in:
ai-chess
2026-05-14 23:18:57 +03:00
parent 4f096953d7
commit 83e2fb8765
3 changed files with 268 additions and 0 deletions
+15
View File
@@ -0,0 +1,15 @@
from __future__ import annotations
import uvicorn
from ai_chess.app import build_app
from ai_chess.state import state
def main() -> None:
app = build_app(state)
uvicorn.run(app, host="127.0.0.1", port=7833, log_level="info")
if __name__ == "__main__":
main()
+178
View File
@@ -0,0 +1,178 @@
from __future__ import annotations
import json
from typing import Any
from fastapi import FastAPI, HTTPException, Request, WebSocket, WebSocketDisconnect
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
import ai_chess.state as state_mod
from ai_chess.mcp_server import TOOL_SCHEMAS, build_tools_for_side
from ai_chess.persistence import list_games, load_game
from ai_chess.settings import save_settings
from ai_chess.sides import Side
PROTOCOL_VERSION = "2025-06-18"
SERVER_NAME = "ai-chess"
def build_app(state: state_mod.AppState) -> FastAPI:
app = FastAPI(title="ai-chess")
# --------- REST ---------
@app.get("/api/state")
async def get_state() -> dict[str, Any]:
if state.game is None:
return {"game": None, "settings": state.settings.model_dump(),
"bindings": {s.value: b.to_dict() for s, b in state.bindings.items()}}
return {
"game": state.game.get_state(),
"settings": state.settings.model_dump(),
"bindings": {s.value: b.to_dict() for s, b in state.bindings.items()},
}
@app.get("/api/games")
async def games_list() -> list[dict[str, Any]]:
return list_games(state_mod.GAMES_DIR)
@app.get("/api/games/{game_id}")
async def game_get(game_id: str) -> dict[str, Any]:
try:
return load_game(state_mod.GAMES_DIR, game_id)
except FileNotFoundError:
raise HTTPException(404, "game not found")
@app.get("/api/games/{game_id}/pgn")
async def game_pgn(game_id: str) -> Any:
try:
data = load_game(state_mod.GAMES_DIR, game_id)
except FileNotFoundError:
raise HTTPException(404, "game not found")
return JSONResponse({"pgn": data["pgn"]})
@app.get("/api/settings")
async def settings_get() -> dict[str, Any]:
return state.settings.model_dump()
@app.post("/api/settings")
async def settings_post(patch: dict[str, Any]) -> dict[str, Any]:
state.settings = save_settings(state_mod.CONFIG_DIR / "settings.json", state.settings, patch)
await state.events.publish({"type": "settings", "settings": state.settings.model_dump()})
return state.settings.model_dump()
@app.post("/api/new-game")
async def new_game_post() -> dict[str, Any]:
# Coordinator wiring happens in Task 16's lifespan. Deferred import to avoid
# ImportError at module load time (coordinator doesn't exist until Task 15).
from ai_chess.coordinator import start_new_game # noqa: PLC0415
await start_new_game(state)
return state.game.get_state() # type: ignore[union-attr]
@app.get("/api/agent-binding/{side}")
async def agent_binding(side: str) -> dict[str, Any]:
s = Side.from_str(side)
b = state.bindings.get(s)
if not b:
raise HTTPException(404, "not bound yet")
return b.to_dict()
# --------- WebSocket ---------
@app.websocket("/ws")
async def ws_endpoint(ws: WebSocket) -> None:
await ws.accept()
q = state.events.subscribe()
snapshot = await get_state()
await ws.send_text(json.dumps({"type": "snapshot", **snapshot}, default=str))
try:
while True:
ev = await q.get()
await ws.send_text(json.dumps(ev, default=str))
except WebSocketDisconnect:
pass
finally:
state.events.unsubscribe(q)
# --------- MCP JSON-RPC ---------
async def handle_mcp(side: Side, body: dict[str, Any]) -> dict[str, Any]:
rid = body.get("id")
method = body.get("method")
params = body.get("params") or {}
def ok(result: Any) -> dict[str, Any]:
return {"jsonrpc": "2.0", "id": rid, "result": result}
def err(code: int, message: str) -> dict[str, Any]:
return {"jsonrpc": "2.0", "id": rid, "error": {"code": code, "message": message}}
if method == "initialize":
return ok({
"protocolVersion": PROTOCOL_VERSION,
"capabilities": {"tools": {"listChanged": False}},
"serverInfo": {"name": f"{SERVER_NAME}:{side.value}", "version": "0.1.0"},
})
if method == "notifications/initialized":
return {} # no response for notifications
if method == "tools/list":
tools = []
for name, schema in TOOL_SCHEMAS.items():
tools.append({
"name": name,
"description": schema["description"],
"inputSchema": schema["inputSchema"],
})
return ok({"tools": tools})
if method == "tools/call":
name = params.get("name")
arguments = params.get("arguments") or {}
tools = build_tools_for_side(side, state)
if name not in tools:
return err(-32601, f"unknown tool: {name}")
try:
result = await tools[name](arguments)
except Exception as e: # tool errors -> isError result
return ok({
"content": [{"type": "text", "text": json.dumps(
{"ok": False, "reason": "exception", "detail": str(e)},
ensure_ascii=False)}],
"isError": True,
})
return ok({
"content": [{"type": "text", "text": json.dumps(result, ensure_ascii=False)}],
"isError": not result.get("ok", True),
})
return err(-32601, f"method not found: {method}")
@app.post("/mcp/{side}")
async def mcp_post(side: str, request: Request) -> Any:
try:
s = Side.from_str(side)
except ValueError:
raise HTTPException(404, "unknown side")
body = await request.json()
if isinstance(body, list): # batch
return [await handle_mcp(s, item) for item in body if isinstance(item, dict)]
return await handle_mcp(s, body)
# --------- static UI ---------
if state_mod.PUBLIC_DIR.exists():
app.mount("/static", StaticFiles(directory=state_mod.PUBLIC_DIR), name="static")
@app.get("/")
async def index() -> FileResponse:
return FileResponse(state_mod.PUBLIC_DIR / "index.html")
@app.get("/games")
async def games_page() -> FileResponse:
return FileResponse(state_mod.PUBLIC_DIR / "games.html")
return app
+75
View File
@@ -0,0 +1,75 @@
import asyncio
import pytest
from fastapi.testclient import TestClient
import ai_chess.state as state_mod
from ai_chess.app import build_app
from ai_chess.chess_game import ChessGame
@pytest.fixture
def client(tmp_path, monkeypatch):
# Use a fresh AppState per test
monkeypatch.setattr(state_mod, "GAMES_DIR", tmp_path / "games")
monkeypatch.setattr(state_mod, "CONFIG_DIR", tmp_path / "config")
monkeypatch.setattr(state_mod, "LOGS_DIR", tmp_path / "logs")
s = state_mod.AppState()
s.game = ChessGame(game_id="t1")
monkeypatch.setattr(state_mod, "state", s)
app = build_app(s)
return TestClient(app)
def test_state_endpoint(client):
r = client.get("/api/state")
assert r.status_code == 200
body = r.json()
assert body["game"]["fen"].startswith("rnbqkbnr")
assert body["game"]["side_to_move"] == "white"
def test_settings_get_post(client):
r = client.get("/api/settings")
assert r.status_code == 200
assert r.json()["allow_draw_resign"] is True
r = client.post("/api/settings", json={"allow_illegal_moves": True})
assert r.status_code == 200
assert r.json()["allow_illegal_moves"] is True
def test_mcp_initialize(client):
r = client.post("/mcp/white", json={
"jsonrpc": "2.0", "id": 1, "method": "initialize",
"params": {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "test", "version": "0"}},
})
assert r.status_code == 200
body = r.json()
assert body["result"]["serverInfo"]["name"].startswith("ai-chess")
def test_mcp_tools_list_and_call(client):
r = client.post("/mcp/white", json={
"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {},
})
names = [t["name"] for t in r.json()["result"]["tools"]]
assert "move" in names and "resign" in names
r = client.post("/mcp/white", json={
"jsonrpc": "2.0", "id": 3, "method": "tools/call",
"params": {"name": "move", "arguments": {"move": "e4", "comment": "го"}},
})
body = r.json()
content = body["result"]["content"][0]["text"]
assert '"ok": true' in content or '"ok":true' in content
assert "e4" in content
def test_mcp_wrong_side_blocked(client):
r = client.post("/mcp/black", json={
"jsonrpc": "2.0", "id": 4, "method": "tools/call",
"params": {"name": "move", "arguments": {"move": "e5"}},
})
text = r.json()["result"]["content"][0]["text"]
assert "not_your_turn" in text