roll_dice
Generate random dice rolls using standard notation like '2d6+3' or '1d20-2' for gaming, probability calculations, or decision-making scenarios.
Instructions
Roll dice using standard notation (e.g., '2d6+3', '1d20-2')
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| notation | Yes | Dice notation (e.g., '2d6+3', '1d20-2') |
Implementation Reference
- src/mcp_dice/server.py:141-161 (handler)MCP tool handler that processes 'roll_dice' tool calls by parsing notation, rolling dice, and returning JSON result.@app.call_tool() async def call_tool( name: str, arguments: Any ) -> Sequence[TextContent | ImageContent | EmbeddedResource]: """Handle tool calls for dice rolling.""" if name != "roll_dice": raise ValueError(f"Unknown tool: {name}") if not isinstance(arguments, dict) or "notation" not in arguments: raise ValueError("Invalid dice roll arguments") try: notation = arguments["notation"] n_dice, n_sides, modifier = parse_dice_notation(notation) roll_result = roll_dice(n_dice, n_sides, modifier) return [TextContent(type="text", text=json.dumps(roll_result, indent=2))] except Exception as e: logger.error(f"Dice rolling error: {str(e)}") raise RuntimeError(f"Dice rolling error: {str(e)}")
- src/mcp_dice/server.py:126-136 (schema)Input schema defining the 'notation' parameter for the roll_dice tool with regex pattern validation.inputSchema={ "type": "object", "properties": { "notation": { "type": "string", "description": "Dice notation (e.g., '2d6+3', '1d20-2')", "pattern": r"^\d+d\d+([+-]\d+)?$", } }, "required": ["notation"], },
- src/mcp_dice/server.py:123-137 (registration)Registration of the 'roll_dice' tool in the MCP server's list_tools method, including name, description, and schema.Tool( name="roll_dice", description="Roll dice using standard notation (e.g., '2d6+3', '1d20-2')", inputSchema={ "type": "object", "properties": { "notation": { "type": "string", "description": "Dice notation (e.g., '2d6+3', '1d20-2')", "pattern": r"^\d+d\d+([+-]\d+)?$", } }, "required": ["notation"], }, )
- src/mcp_dice/server.py:46-82 (helper)Core helper function that performs the actual dice rolling logic, validation, and result formatting.def roll_dice(n_dice: int, n_sides: int, modifier: int = 0) -> dict[str, Any]: """ Roll the specified number of dice with given sides and add modifier. Args: n_dice: Number of dice to roll n_sides: Number of sides on each die modifier: Numeric modifier to add to the total (can be negative) Returns: Dictionary containing roll results and metadata """ if n_dice < 1: raise ValueError("Number of dice must be positive") if n_sides < 2: raise ValueError("Number of sides must be at least 2") rolls = [random.randint(1, n_sides) for _ in range(n_dice)] roll_sum = sum(rolls) total = roll_sum + modifier # Format the notation with modifier notation = f"{n_dice}d{n_sides}" if modifier > 0: notation += f"+{modifier}" elif modifier < 0: notation += f"{modifier}" return { "rolls": rolls, "sum": roll_sum, "modifier": modifier, "total": total, "notation": notation, "timestamp": datetime.now().isoformat(), }
- src/mcp_dice/server.py:21-43 (helper)Helper function to parse dice notation strings into parameters for rolling.def parse_dice_notation(notation: str) -> Tuple[int, int, int]: """ Parse dice notation (e.g., '2d6+3') into number of dice, sides, and modifier. Args: notation: Dice notation string (e.g., '2d6+3', '1d20-2') Returns: Tuple of (number of dice, number of sides, modifier) """ # Updated pattern to support optional modifier pattern = re.compile(r"^(\d+)d(\d+)(?:([+-]\d+))?$") match = pattern.match(notation) if not match: raise ValueError(f"Invalid dice notation: {notation}") n_dice, n_sides = map(int, match.groups()[:2]) # Parse modifier if present, default to 0 if not modifier_str = match.group(3) modifier = int(modifier_str) if modifier_str else 0 return n_dice, n_sides, modifier