Skip to main content
Glama
zazencodes

Random Number MCP

by zazencodes

random_choices

Choose random items from a list, with optional weights to influence selection probabilities. Ideal for sampling, simulations, or random assignments.

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
NameRequiredDescriptionDefault
populationYes
kNo
weightsNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Core implementation of random_choices: calls random.choices() with validation for population, k, and weights.
    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)
  • MCP server registration of random_choices tool with app.tool() decorator; handles weights as optional JSON string.
    @app.tool()
    def random_choices(
        population: list[str | int | float | bool],
        k: int = 1,
        weights: list[int | float] | str | None = None,
    ) -> list[str | int | float | bool]:
        """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)
  • @app.tool() decorator registration of the random_choices function as an MCP tool.
    @app.tool()
  • validate_positive_int: validates that k is a non-negative integer.
    def validate_positive_int(value: int, name: str) -> None:
        """Validate that a value is a positive integer."""
        if not isinstance(value, int):
            raise TypeError(f"{name} must be an integer, got {type(value).__name__}")
        if value < 0:
            raise ValueError(f"{name} must be non-negative, got {value}")
  • validate_weights_match_population: validates weights list length matches population length.
    def validate_weights_match_population(
        population: list[Any], weights: list[int | float]
    ) -> None:
        """Validate that weights list matches population length."""
        if len(weights) != len(population):
            raise ValueError(
                f"Weights list length ({len(weights)}) must match "
                f"population length ({len(population)})"
            )
Behavior4/5

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

With no annotations, the description carries full burden for behavioral transparency. It clearly states the sampling method (with replacement) and optional weighting. However, it does not detail edge cases like empty population or weight mismatches, which are typical for such functions.

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 highly concise with two purposeful sentences and a parameter list. Every part contributes meaning without redundancy.

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

Completeness4/5

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

The description covers the core functionality and return type adequately. Given the presence of an output schema (implied by 'Returns list'), it is mostly complete. Minor omissions like error conditions or weight normalization do not detract significantly.

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

Parameters4/5

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

The description adds significant value beyond the input schema by explaining each parameter: population is the list, k is the number of draws, and weights are optional and default to equal weights. This clarifies the purpose of each parameter beyond their types.

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 tool selects k items from a population with replacement, optionally weighted. This distinguishes it from siblings like random_sample (without replacement) and random_float (single value).

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 explains what the tool does but does not explicitly state when to use it over alternatives. The context of sibling names implies differentiation, but no direct guidance is provided.

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/zazencodes/random-number-mcp'

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