Skip to main content
Glama
yamaton

mcp-dice

by yamaton

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
NameRequiredDescriptionDefault
notationYesDice notation (e.g., '2d6+3', '1d20-2')

Implementation Reference

  • 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)}")
  • 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"],
    },
  • 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"],
        },
    )
  • 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(),
        }
  • 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
Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/yamaton/mcp-dice'

If you have feedback or need assistance with the MCP directory API, please join our Discord server