mcp_server.py•3.81 kB
import asyncio
import logging
import os
import random
from fastmcp import FastMCP
logger = logging.getLogger(__name__)
logging.basicConfig(format="[%(levelname)s]: %(message)s", level=logging.INFO)
mcp = FastMCP("Simple Guess Number Game")
games = {}
@mcp.tool()
def start_game(user_id: str = "default_user") -> str:
"""Start a new number guessing game (1-100).
Args:
user_id: Unique identifier for the player (default: "default_user")
Returns:
Game start message
"""
number = random.randint(1, 100)
games[user_id] = {
"secret_number": number,
"attempts": 0
}
logger.info(f"New game started for user: {user_id}")
return "New game started! I've picked a number between 1 and 100. Try to guess it!"
@mcp.tool()
def make_guess(user_id: str, guess: int) -> str:
"""Make a guess in the number guessing game.
Args:
user_id: Unique identifier for the player
guess: Your guess (number between 1 and 100)
Returns:
Result of your guess with feedback
"""
if not isinstance(guess, int) or guess < 1 or guess > 100:
return "Please guess a number between 1 and 100!"
if user_id not in games:
return "No active game found. Start a new game first!"
game = games[user_id]
secret = game["secret_number"]
game["attempts"] += 1
logger.info(f"User {user_id} guessed {guess} (attempt #{game['attempts']})")
if guess < secret:
return f"Too low! Try a higher number. (Attempt #{game['attempts']})"
elif guess > secret:
return f"Too high! Try a lower number. (Attempt #{game['attempts']})"
else:
# Game won!
attempts = game["attempts"]
del games[user_id] # Remove completed game
logger.info(f"User {user_id} won in {attempts} attempts!")
if attempts == 1:
return f"Perfect! You got {guess} in just 1 try!"
elif attempts <= 5:
return f"Excellent! You found {guess} in {attempts} attempts!"
else:
return f"Well done! You found {guess} in {attempts} attempts!"
@mcp.tool()
def game_status(user_id: str = "default_user") -> str:
"""Check the status of your current game.
Args:
user_id: Unique identifier for the player (default: "default_user")
Returns:
Current game status
"""
if user_id not in games:
return "No active game. Start a new game first!"
game = games[user_id]
return f"Game Status: {game['attempts']} attempts made. Keep guessing between 1-100!"
@mcp.tool()
def quit_game(user_id: str = "default_user") -> str:
"""Quit the current game and reveal the answer.
Args:
user_id: Unique identifier for the player (default: "default_user")
Returns:
Game quit confirmation with the secret number
"""
if user_id not in games:
return "No active game to quit."
secret = games[user_id]["secret_number"]
attempts = games[user_id]["attempts"]
del games[user_id]
logger.info(f"User {user_id} quit game")
return f"Game ended! The secret number was {secret}. You made {attempts} attempts."
@mcp.tool()
def get_server_info() -> str:
"""Get basic server information.
Returns:
Server status
"""
active_games = len(games)
return f"Simple Guess Number Game Server - Port: {os.getenv('PORT', 8080)} - Active Games: {active_games}"
if __name__ == "__main__":
port = int(os.getenv('PORT', 8080))
logger.info(f"Starting Simple Guess Number Game on port {port}")
asyncio.run(
mcp.run_async(
transport="streamable-http",
host="0.0.0.0",
port=port,
)
)