roll_dice
Simulate dice rolls using standard notation to generate random numbers for games, decisions, or probability testing.
Instructions
Roll the dice with the given notation
Tool call template
Replace each placeholder with a value matching the input schema. Only required parameters are included; add optional parameters as needed.
{
"id": 1,
"jsonrpc": "2.0",
"method": "tools/call",
"params": {
"arguments": {
"notation": "<notation>"
},
"name": "roll_dice"
}
}Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| notation | Yes | ||
| num_rolls | No |
Implementation Reference
- server.py:23-27 (handler)The main handler function for the 'roll_dice' tool, decorated with @mcp.tool() for registration in the MCP server. It creates a DiceRoller instance and returns its string representation containing the roll results.
@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:4-47 (helper)The DiceRoller class implements the core dice rolling logic: parses notation like '2d20k1', rolls random dice, keeps highest N rolls, supports multiple rolls, and formats output string used by the tool handler.
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+))?") 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 def roll_multiple(self): """Roll the dice multiple times according to num_rolls""" results = [] for _ in range(self.num_rolls): rolls, kept_rolls = self.roll_dice() results.append({ "rolls": rolls, "kept": kept_rolls, "total": sum(kept_rolls) }) return results 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) - server.py:10-10 (registration)Import of the DiceRoller helper class used in the roll_dice tool implementation.
from dice_roller import DiceRoller