random_choices
Select k items from a population with optional weighted probabilities. Use this tool for random sampling with replacement in applications requiring weighted or unbiased selections.
Instructions
Choose k items from population with replacement, optionally weighted.
Args: population: List of items to choose from k: Number of items to choose (default 1) weights: Optional weights for each item (default None for equal weights)
Returns: List of k chosen items
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| k | No | ||
| population | Yes | ||
| weights | No |
Implementation Reference
- src/random_number_mcp/server.py:42-67 (handler)MCP tool handler for 'random_choices'. Handles optional JSON string weights and delegates core logic to tools.random_choices.@app.tool() def random_choices( population: list[Any], k: int = 1, weights: list[int | float] | str | None = None, ) -> list[Any]: """Choose k items from population with replacement, optionally weighted. Args: population: List of items to choose from k: Number of items to choose (default 1) weights: Optional weights for each item (default None for equal weights) Returns: List of k chosen items """ numeric_weights: list[int | float] | None = None if isinstance(weights, str): try: numeric_weights = json.loads(weights) except json.JSONDecodeError as e: raise ValueError(f"Invalid JSON string for weights: {weights}") from e else: numeric_weights = weights return tools.random_choices(population, k, numeric_weights)
- src/random_number_mcp/tools.py:57-80 (helper)Core helper function implementing random choices logic using Python's random.choices, with input validation.def random_choices( population: list[Any], k: int = 1, weights: list[int | float] | None = None ) -> list[Any]: """Choose k items from population with replacement, optionally weighted. Args: population: List of items to choose from k: Number of items to choose (default 1) weights: Optional weights for each item (default None for equal weights) Returns: List of k chosen items Raises: ValueError: If population is empty, k < 0, or weights length doesn't match TypeError: If k is not an integer """ validate_list_not_empty(population, "population") validate_positive_int(k, "k") if weights is not None: validate_weights_match_population(population, weights) return random.choices(population, weights=weights, k=k)