roll_dice
Generate random dice rolls using standard notation for games, simulations, or decision-making scenarios. Specify dice type and quantity to produce randomized outcomes.
Instructions
Roll the dice with the given notation
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| notation | Yes | ||
| num_rolls | No |
Implementation Reference
- server.py:19-24 (handler)The main handler function for the 'roll_dice' MCP tool. It is registered via @mcp.tool() decorator and executes the dice rolling by instantiating DiceRoller and returning its string representation.@mcp.tool() def roll_dice(notation: str, num_rolls: int = 1) -> str: """Roll the dice with the given notation""" roller = DiceRoller(notation, num_rolls) return str(roller)
- dice_roller.py:10-23 (helper)Core helper method in DiceRoller class that parses dice notation (e.g., 2d20k1), rolls the dice, sorts, keeps top N, and returns rolls and kept rolls.def roll_dice(self): match = self.dice_pattern.match(self.notation) if not match: raise ValueError("Invalid dice notation") num_dice = int(match.group(1)) dice_sides = int(match.group(2)) keep = int(match.group(4)) if match.group(4) else num_dice rolls = [random.randint(1, dice_sides) for _ in range(num_dice)] rolls.sort(reverse=True) kept_rolls = rolls[:keep] return rolls, kept_rolls
- dice_roller.py:37-47 (helper)String representation method of DiceRoller that performs the actual rolling (single or multiple) and formats the output string returned by the tool.def __str__(self): if self.num_rolls == 1: rolls, kept_rolls = self.roll_dice() return f"ROLLS: {', '.join(map(str, rolls))} -> RETURNS: {sum(kept_rolls)}" else: results = self.roll_multiple() result_strs = [] for i, result in enumerate(results, 1): result_strs.append(f"Roll {i}: ROLLS: {', '.join(map(str, result['rolls']))} -> RETURNS: {result['total']}") return "\n".join(result_strs)
- dice_roller.py:4-9 (helper)DiceRoller class initializer and regex pattern for parsing dice notation like NdSk.class DiceRoller: def __init__(self, notation, num_rolls=1): self.notation = notation self.num_rolls = num_rolls self.dice_pattern = re.compile(r"(\d+)d(\d+)(k(\d+))?")
- server.py:19-24 (registration)Registration of the 'roll_dice' tool using FastMCP's @mcp.tool() decorator, with input schema defined by function parameters.@mcp.tool() def roll_dice(notation: str, num_rolls: int = 1) -> str: """Roll the dice with the given notation""" roller = DiceRoller(notation, num_rolls) return str(roller)