chess-agent / utils /tools.py
czakop's picture
create chess agent
70d877e
import chess
from langchain_core.tools import BaseTool, tool
from langchain_mcp_adapters.client import MultiServerMCPClient
def create_base_tools(board: chess.Board) -> list[BaseTool]:
"""Create tools for interacting with a chess board.
Args:
board (chess.Board): The chess board to interact with.
Returns:
list[BaseTool]: A list of tools for interacting with the chess board.
"""
@tool
def get_fen() -> str:
"""Get the current FEN string of the chess board."""
return board.fen()
@tool
def set_fen(fen: str) -> str:
"""Set the chess board to a specific FEN string.
Don't use when you are playing a game, use the `make_move` tool instead.
Args:
fen (str): The FEN string to set the board to.
"""
try:
board.set_fen(fen)
return board.fen()
except ValueError as e:
return str(e)
@tool
def make_move(move: str) -> str:
"""Make a move on the chess board and return the new FEN string.
Args:
move (str): The move in UCI format (e.g., "e2e4").
"""
try:
chess_move = chess.Move.from_uci(move)
if chess_move in board.legal_moves:
board.push(chess_move)
return board.fen()
else:
return "Illegal move"
except Exception as e:
return str(e)
return [
get_fen,
set_fen,
make_move,
]
async def create_mcp_tools(
url: str = "http://localhost:7860/gradio_api/mcp/sse", transport: str = "sse"
) -> list[BaseTool]:
mcp_client = MultiServerMCPClient(
{
"chess": {
"url": url,
"transport": transport,
}
}
)
return await mcp_client.get_tools()