roll_dice
Simulate dice rolls using standard notation (e.g., "2d6", "3d6+5") for tabletop games, RPGs, or probability testing. Input an array of dice codes to generate random outcomes.
Instructions
Roll a set of dice using standard dice notation (e.g., "2d6" for two six-sided dice, "3d6+5" for three six-sided dice plus 5)
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| dice | Yes | Array of dice to roll |
Implementation Reference
- src/handlers/roll-dice.handler.ts:80-102 (handler)The main handler function that executes the roll_dice tool, parsing arguments, rolling dice, and returning results as JSON.export const rollDiceHandler = async ( request: CallToolRequest ): Promise<CallToolResult> => { const args = request.params.arguments as { dice: string[] }; if (!args.dice || args.dice.length === 0) { throw new McpError( ErrorCode.InvalidParams, 'Must specify at least one die to roll' ); } const results = args.dice.map(dice => rollDiceSet(dice)); return { content: [ { type: 'text', text: JSON.stringify(results, null, 2) } ] }; };
- Tool specification including name, description, and input schema for validating roll_dice parameters.export const toolSpec = { name: 'roll_dice', description: 'Roll a set of dice using standard dice notation (e.g., "2d6" for two six-sided dice, "3d6+5" for three six-sided dice plus 5)', inputSchema: { type: 'object' as const, properties: { dice: { type: 'array', items: { type: 'string', description: 'Dice notation (e.g., "2d6", "1d20", "4d4")' }, description: 'Array of dice to roll' } }, required: ['dice'] } };
- src/index.ts:24-24 (registration)Registers the roll_dice tool handler in the main server registry.registry.register('tools/call', 'roll_dice', rollDiceHandler as Handler);
- Helper function that rolls a single set of dice, computes rolls and total.function rollDiceSet(notation: string): DiceRoll { const { count, sides, modifier } = parseDiceNotation(notation); const rolls = Array.from({ length: count }, () => rollDie(sides)); const rollTotal = rolls.reduce((a, b) => a + b, 0); const total = rollTotal + modifier; return { dice: notation, rolls, modifier, total }; }
- Helper function to parse dice notation like '2d6+5' into count, sides, and modifier.function parseDiceNotation(notation: string): { count: number; sides: number; modifier: number } { const match = notation.toLowerCase().match(/^(\d+)d(\d+)([+-]\d+)?$/); if (!match) { throw new McpError( ErrorCode.InvalidParams, 'Invalid dice notation' ); } const count = parseInt(match[1]); const sides = parseInt(match[2]); const modifier = match[3] ? parseInt(match[3]) : 0; // If no modifier, default to 0 if (count <= 0) { throw new McpError( ErrorCode.InvalidParams, 'Number of dice must be positive' ); } if (sides <= 0) { throw new McpError( ErrorCode.InvalidParams, 'Die size must be positive' ); } return { count, sides, modifier }; }