roll_dice
Simulate dice rolls using standard notation (e.g., '2d6+3', '1d20-2') for tabletop games, RPGs, or probability testing. Input the notation to generate results instantly.
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:46-82 (handler)Core function implementing the dice rolling logic: validates inputs, generates random rolls for multiple dice, applies modifier, formats notation, and returns structured result dictionary.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:119-139 (registration)Registers the 'roll_dice' tool with the MCP server via list_tools handler, including name, description, and input schema definition.@app.list_tools() async def list_tools() -> list[Tool]: """List available dice rolling tools.""" return [ 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:141-161 (handler)MCP call_tool handler that dispatches to roll_dice for the 'roll_dice' tool: validates input, parses notation, executes roll, and returns JSON result as TextContent.@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 for roll_dice tool: object with required 'notation' string validated by regex pattern for dice notation.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:21-43 (helper)Utility function to parse dice notation string into tuple of (n_dice, n_sides, modifier), used by both resource and tool handlers.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