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:
@@ -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
|
||||
Reference in New Issue
Block a user