Spaces:
Sleeping
Sleeping
File size: 18,427 Bytes
7bfb4cb 4c909d9 7bfb4cb 4c909d9 a1ad91c 7bfb4cb |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 |
import os
import asyncio
from dotenv import load_dotenv
from mcp.server.fastmcp import FastMCP
from fastapi.responses import FileResponse, HTMLResponse
from app import Room, rooms, get_ai_move_for_room, get_ai_chat_for_room
load_dotenv()
# --- MCP Server Setup ---
mcp = FastMCP(
name="TicTacToeRooms",
host="0.0.0.0",
port=7860,
)
# --- Global state for current user session ---
current_session = {
'active_room_id': None,
'username': 'MCPPlayer'
}
# --- MCP Tools ---
@mcp.tool()
def create_room() -> dict:
"""
Create a new tic-tac-toe game room.
Returns:
dict: Room information including room ID and initial markdown state
"""
global current_session
try:
room = Room()
rooms[room.id] = room
current_session['active_room_id'] = room.id
return {
"status": "success",
"room_id": room.id,
"message": f"Created new tic-tac-toe room: {room.id}",
"markdown_state": room.to_markdown(),
"instructions": "Use make_move() to play or send_chat() to talk with Mistral AI",
"game_info": {
"your_symbol": "X",
"ai_symbol": "O",
"board_positions": "0-8 (left to right, top to bottom)"
}
}
except Exception as e:
return {
"status": "error",
"message": f"Failed to create room: {str(e)}"
}
@mcp.tool()
def get_room_state(room_id: str = None) -> dict:
"""
Get the current state of a tic-tac-toe room in markdown format.
Args:
room_id (str, optional): Room ID to check (uses current active room if not provided)
Returns:
dict: Current room state with markdown representation
"""
global current_session
try:
# Use provided room_id or current active room
target_room_id = room_id or current_session.get('active_room_id')
if not target_room_id:
return {
"status": "error",
"message": "No active room. Create a room first using create_room()."
}
if target_room_id not in rooms:
return {
"status": "error",
"message": f"Room {target_room_id} not found. It may have been cleaned up."
}
room = rooms[target_room_id]
return {
"status": "success",
"room_id": target_room_id,
"markdown_state": room.to_markdown(),
"game_status": room.game_status,
"current_player": room.current_player,
"moves_made": room.moves_count,
"your_turn": room.current_player == 'X' and room.game_status == 'active'
}
except Exception as e:
return {
"status": "error",
"message": f"Failed to get room state: {str(e)}"
}
@mcp.tool()
async def make_move(position: int, room_id: str = None) -> dict:
"""
Make a move in a tic-tac-toe game. This will also trigger the AI's response move.
Args:
position (int): Board position (0-8, left to right, top to bottom)
room_id (str, optional): Room ID (uses current active room if not provided)
Returns:
dict: Result of your move and the AI's response with updated game state
"""
global current_session
try:
# Use provided room_id or current active room
target_room_id = room_id or current_session.get('active_room_id')
if not target_room_id:
return {
"status": "error",
"message": "No active room. Create a room first using create_room()."
}
if target_room_id not in rooms:
return {
"status": "error",
"message": f"Room {target_room_id} not found."
}
room = rooms[target_room_id]
# Validate move
if position < 0 or position > 8:
return {
"status": "error",
"message": "Invalid position. Use 0-8 (left to right, top to bottom)."
}
if room.game_status != 'active':
return {
"status": "error",
"message": f"Game is over. Status: {room.game_status}",
"markdown_state": room.to_markdown()
}
if room.current_player != 'X':
return {
"status": "error",
"message": "It's not your turn! Wait for AI to move.",
"markdown_state": room.to_markdown()
}
# Make human move
if not room.make_move(position, 'X'):
return {
"status": "error",
"message": f"Invalid move! Position {position} may already be occupied.",
"markdown_state": room.to_markdown()
}
result_message = f"โ
You played X at position {position}\n\n"
# Check if game ended after human move
if room.game_status != 'active':
if room.winner == 'X':
result_message += "๐ Congratulations! You won!\n\n"
else:
result_message += "๐ค It's a draw!\n\n"
result_message += room.to_markdown()
return {
"status": "success",
"message": result_message,
"game_over": True,
"winner": room.winner
}
# Get AI move
try:
ai_response = get_ai_move_for_room(room)
if ai_response and 'move' in ai_response:
room.make_move(ai_response['move'], 'O')
if 'message' in ai_response:
room.add_chat_message(ai_response['message'], 'ai')
result_message += f"๐ค Mistral AI played O at position {ai_response['move']}\n"
if 'message' in ai_response:
result_message += f"๐ฌ Mistral says: \"{ai_response['message']}\"\n\n"
else:
result_message += "\n"
# Check if AI won
if room.game_status == 'won' and room.winner == 'O':
result_message += "๐ Mistral AI wins this round!\n\n"
elif room.game_status == 'draw':
result_message += "๐ค It's a draw!\n\n"
else:
result_message += "โ ๏ธ AI move failed, but you can continue\n\n"
except Exception as e:
result_message += f"โ ๏ธ AI move error: {str(e)}\n\n"
result_message += room.to_markdown()
return {
"status": "success",
"message": result_message,
"game_over": room.game_status != 'active',
"winner": room.winner if room.game_status == 'won' else None,
"your_turn": room.current_player == 'X' and room.game_status == 'active'
}
except Exception as e:
return {
"status": "error",
"message": f"Failed to make move: {str(e)}"
}
@mcp.tool()
async def send_chat(message: str, room_id: str = None) -> dict:
"""
Send a chat message to Mistral AI in the current game room.
Args:
message (str): Your message to send to the AI
room_id (str, optional): Room ID (uses current active room if not provided)
Returns:
dict: Your message and the AI's response with updated room state
"""
global current_session
try:
# Use provided room_id or current active room
target_room_id = room_id or current_session.get('active_room_id')
if not target_room_id:
return {
"status": "error",
"message": "No active room. Create a room first using create_room()."
}
if target_room_id not in rooms:
return {
"status": "error",
"message": f"Room {target_room_id} not found."
}
room = rooms[target_room_id]
# Add user message
room.add_chat_message(message, 'user')
# Get AI response
ai_response = get_ai_chat_for_room(room, message)
room.add_chat_message(ai_response, 'ai')
result_message = f"๐ฌ **You:** {message}\n๐ฌ **Mistral AI:** {ai_response}\n\n"
result_message += room.to_markdown()
return {
"status": "success",
"message": result_message,
"your_message": message,
"ai_response": ai_response
}
except Exception as e:
return {
"status": "error",
"message": f"Failed to send chat: {str(e)}"
}
@mcp.tool()
def list_rooms() -> dict:
"""
List all active tic-tac-toe game rooms.
Returns:
dict: List of active rooms with their status
"""
try:
if not rooms:
return {
"status": "success",
"message": "No active rooms. Use create_room() to start a new game!",
"active_rooms": [],
"count": 0
}
room_list = []
for room_id, room in rooms.items():
room_info = {
"room_id": room_id,
"game_status": room.game_status,
"current_player": room.current_player,
"moves_count": room.moves_count,
"winner": room.winner,
"is_your_turn": room.current_player == 'X' and room.game_status == 'active',
"is_active": current_session.get('active_room_id') == room_id
}
room_list.append(room_info)
active_room_id = current_session.get('active_room_id')
message = f"Found {len(room_list)} active rooms."
if active_room_id:
message += f" Current active room: {active_room_id}"
return {
"status": "success",
"message": message,
"active_rooms": room_list,
"count": len(room_list),
"current_active_room": active_room_id
}
except Exception as e:
return {
"status": "error",
"message": f"Failed to list rooms: {str(e)}"
}
@mcp.tool()
def switch_room(room_id: str) -> dict:
"""
Switch to a different active room.
Args:
room_id (str): Room ID to switch to
Returns:
dict: Confirmation of room switch with current state
"""
global current_session
try:
if room_id not in rooms:
return {
"status": "error",
"message": f"Room {room_id} not found. Use list_rooms() to see available rooms."
}
current_session['active_room_id'] = room_id
room = rooms[room_id]
return {
"status": "success",
"message": f"Switched to room {room_id}",
"room_id": room_id,
"markdown_state": room.to_markdown(),
"your_turn": room.current_player == 'X' and room.game_status == 'active'
}
except Exception as e:
return {
"status": "error",
"message": f"Failed to switch room: {str(e)}"
}
@mcp.tool()
def get_help() -> dict:
"""
Get help information about playing tic-tac-toe.
Returns:
dict: Instructions and tips for playing the game
"""
return {
"status": "success",
"message": "Tic-Tac-Toe Game Help",
"instructions": {
"how_to_play": [
"1. Create a new game room with create_room()",
"2. Make moves using make_move(position) where position is 0-8",
"3. Chat with Mistral AI using send_chat('your message')",
"4. Check game state anytime with get_room_state()"
],
"board_layout": {
"description": "Board positions (0-8):",
"layout": [
"0 | 1 | 2",
"---------",
"3 | 4 | 5",
"---------",
"6 | 7 | 8"
]
},
"symbols": {
"you": "X (you go first)",
"ai": "O (Mistral AI)"
},
"tips": [
"The AI has personality and will trash talk!",
"You can have multiple rooms active at once",
"Use list_rooms() to see all your games",
"Use switch_room(room_id) to change between games"
]
},
"available_commands": [
"create_room() - Start a new game",
"make_move(position) - Make your move (0-8)",
"send_chat('message') - Chat with AI",
"get_room_state() - Check current game",
"list_rooms() - See all active games",
"switch_room(room_id) - Change active room",
"get_help() - Show this help"
]
}
@mcp.tool()
async def wait_5_seconds() -> dict:
"""
Wait for 5 seconds. Useful for giving the AI time to respond or timing operations.
Returns:
dict: Status of the wait operation
"""
try:
await asyncio.sleep(5)
return {
"status": "success",
"message": "Waited 5 seconds successfully"
}
except Exception as e:
return {
"status": "error",
"message": f"Failed to wait: {str(e)}"
}
# Add web UI endpoints using FastMCP's underlying FastAPI
@mcp.get("/")
async def root():
return {
"name": "Tic-Tac-Toe MCP Server",
"status": "running",
"mcp_tools": ["create_room", "make_move", "send_chat", "get_room_state", "list_rooms"],
"web_ui": "/rooms-ui",
"description": "MCP server for LeChat + optional web UI for testing"
}
@mcp.get("/rooms-ui")
async def serve_ui():
return FileResponse("room_game.html")
@mcp.get("/room_game.js")
async def serve_js():
return FileResponse("room_game.js")
# Also serve Flask app routes for the room system
from app import app as flask_app
from fastapi import Request
import json
@mcp.post("/rooms")
async def create_room_endpoint():
room = Room()
rooms[room.id] = room
return {"room_id": room.id, "status": "created", "room_data": room.to_dict()}
@mcp.get("/rooms/{room_id}")
async def get_room_endpoint(room_id: str):
if room_id not in rooms:
return {"error": "Room not found"}
room = rooms[room_id]
return {"room_id": room_id, "room_data": room.to_dict(), "markdown": room.to_markdown()}
@mcp.post("/rooms/{room_id}/move")
async def move_endpoint(room_id: str, request: Request):
if room_id not in rooms:
return {"error": "Room not found"}
data = await request.json()
room = rooms[room_id]
position = data.get("position")
if position is None or position < 0 or position > 8:
return {"error": "Invalid position"}
# Make human move
if not room.make_move(position, 'X'):
return {"error": "Invalid move"}
# Check if game ended
if room.game_status != 'active':
return {"room_data": room.to_dict(), "markdown": room.to_markdown(), "ai_move": None}
# Get AI move with fallback
try:
ai_response = get_ai_move_for_room(room)
if ai_response and 'move' in ai_response:
ai_move = ai_response['move']
if 0 <= ai_move <= 8 and room.board[ai_move] == '':
room.make_move(ai_move, 'O')
if 'message' in ai_response:
room.add_chat_message(ai_response['message'], 'ai')
else:
# Fallback move
empty_positions = [i for i in range(9) if room.board[i] == '']
if empty_positions:
fallback_move = empty_positions[0]
room.make_move(fallback_move, 'O')
room.add_chat_message("Technical hiccup, but still playing! ๐ค", 'ai')
return {"room_data": room.to_dict(), "markdown": room.to_markdown(), "ai_move": ai_response}
except Exception as e:
# Fallback on error
empty_positions = [i for i in range(9) if room.board[i] == '']
if empty_positions:
fallback_move = empty_positions[0]
room.make_move(fallback_move, 'O')
room.add_chat_message("Connection issues, but improvising! ๐
", 'ai')
return {"room_data": room.to_dict(), "markdown": room.to_markdown(), "ai_move": {"move": fallback_move if empty_positions else None}}
@mcp.post("/rooms/{room_id}/chat")
async def chat_endpoint(room_id: str, request: Request):
if room_id not in rooms:
return {"error": "Room not found"}
data = await request.json()
room = rooms[room_id]
user_message = data.get("message", "")
if not user_message.strip():
return {"error": "Empty message"}
room.add_chat_message(user_message, 'user')
try:
ai_response = get_ai_chat_for_room(room, user_message)
room.add_chat_message(ai_response, 'ai')
return {"room_data": room.to_dict(), "markdown": room.to_markdown(), "ai_response": ai_response}
except Exception as e:
return {"error": "AI chat failed"}
# --- Server Execution ---
if __name__ == "__main__":
print(f"Tic-Tac-Toe Rooms MCP Server starting on port 7860...")
print("Available game features:")
print("- Create multiple game rooms")
print("- Play against Mistral AI with personality")
print("- Real-time chat with the AI")
print("- Markdown state representation")
print("- Room management and switching")
print()
print("MCP Tools available:")
print("- create_room()")
print("- make_move(position)")
print("- send_chat(message)")
print("- get_room_state()")
print("- list_rooms()")
print("- get_help()")
print()
print("This MCP server is ready for LeChat integration!")
print("Running Tic-Tac-Toe MCP server with SSE transport")
mcp.run(transport="sse") |