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
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It describes the action but lacks behavioral details such as whether this is a deterministic or random process, any rate limits, or what the output format might be. The description is minimal and does not compensate for the absence of annotations.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that front-loads the purpose and provides clear examples. There is no wasted information, making it appropriately concise and well-structured for its purpose.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's low complexity (one parameter, no output schema, no annotations), the description is adequate but has gaps. It explains the input but lacks details on output or behavioral context, making it minimally viable but not fully complete for an agent to understand all aspects without additional inference.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema description coverage is 100%, so the schema already documents the single parameter 'notation' with a description and pattern. The description adds minimal value by restating the parameter concept with examples, aligning with the baseline score when schema coverage is high.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('Roll dice') and resource ('using standard notation'), with examples provided. It precisely defines what the tool does without being tautological, and since there are no sibling tools, no differentiation is needed.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage by providing examples of dice notation, but it does not explicitly state when to use this tool versus alternatives. Since there are no sibling tools, no explicit alternatives are mentioned, leaving usage context somewhat implied rather than fully guided.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

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