Skip to main content
Glama

generate_random_weighted

Select options randomly based on predefined weights for use in lottery systems, weighted item drops, task assignment, or A/B testing with customizable probability distributions.

Instructions

Weighted Random Selector

Randomly select an option based on weights

Args:
    options (List[str]): List of options
    weights (List[int]): Corresponding weight list (0-1000)
    salt (str, optional): Random number salt value. Defaults to "".

Returns:
    str: JSON string containing the selection result

Application Scenarios:
1. Lottery systems (prizes with different probabilities)
2. Random drops (weighted item drops)
3. Task assignment (based on priority)
4. A/B testing (experiment groups with different ratios)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
optionsYes
saltNo
weightsYes

Implementation Reference

  • main.py:92-112 (handler)
    The handler function for the MCP tool 'generate_random_weighted', decorated with @mcp.tool() for registration. It receives input parameters and delegates execution to the weighted_random_selector helper in utils.py, returning the result as a string.
    @mcp.tool()
    async def generate_random_weighted(options: List[str], weights: List[int], salt: str = "") -> str:
        """Weighted Random Selector
        
        Randomly select an option based on weights
        
        Args:
            options (List[str]): List of options
            weights (List[int]): Corresponding weight list (0-1000)
            salt (str, optional): Random number salt value. Defaults to "".
        
        Returns:
            str: JSON string containing the selection result
        
        Application Scenarios:
        1. Lottery systems (prizes with different probabilities)
        2. Random drops (weighted item drops)
        3. Task assignment (based on priority)
        4. A/B testing (experiment groups with different ratios)
        """
        return await weighted_random_selector(options, weights, salt)
  • The core helper function implementing the weighted random selection logic. It derives a seed from blockchain block hashes and salt, normalizes weights, and uses numpy.random.choice to select an option probabilistically.
    async def weighted_random_selector(options: List[str], weights: List[int], salt: str = "") -> Dict:
        """
        Weighted random selector
        
        Randomly select an option based on weights
        
        Args:
            options: List of options to choose from
            weights: List of weights for each option (0-1000)
            salt: Optional salt value for additional randomness
            
        Returns:
            Dict containing selected option and selection metadata
        """
        if len(options) != len(weights):
            raise ValueError("Options and weights must have the same length")
        random_num = await get_random_str()
        if not random_num:
            return {"error": "Failed to get random number"}
            
        request_id = generate_request_id(random_num)
        seed = _derive_seed(request_id, salt)
        
        np.random.seed(seed)
        # Normalize weights
        weights_array = np.array(weights, dtype=float)
        weights_normalized = weights_array / np.sum(weights_array)
        
        # Select based on weights
        selection_index = np.random.choice(len(options), p=weights_normalized)
        selected_option = options[selection_index]
            
        result = {
            "requestId": request_id,
            "selectedOption": selected_option,
            "selectionIndex": int(selection_index)
        }
            
        return result
Behavior3/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It explains the core functionality (weighted random selection) and return format (JSON string), but lacks details on potential side effects, error handling, or performance characteristics. It adequately describes what the tool does but could benefit from more behavioral context.

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

Conciseness4/5

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

The description is well-structured with clear sections (purpose, args, returns, scenarios) and front-loaded key information. It's appropriately sized but includes some redundancy (e.g., restating 'Weighted Random Selector' in the first line). Every sentence adds value, though minor trimming could improve conciseness.

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?

For a tool with 3 parameters, no annotations, and no output schema, the description is moderately complete. It covers purpose, parameters, returns, and usage scenarios, but lacks details on error cases, output structure beyond 'JSON string,' or how it differs from siblings. Given the complexity, it's adequate but has gaps in full contextual understanding.

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?

Given 0% schema description coverage, the description compensates by explaining parameters in the 'Args' section: options as a list of strings, weights as corresponding integers (0-1000), and salt as an optional string with a default. This adds meaningful semantics beyond the bare schema, though it doesn't fully detail validation rules or interdependencies.

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

Purpose4/5

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

The description clearly states the tool's purpose: 'Weighted Random Selector' and 'Randomly select an option based on weights.' It specifies the verb (select) and resource (option) with the weighted mechanism. However, it doesn't explicitly differentiate from sibling tools like 'generate_basic_random' or 'generate_rarity,' which might also involve random selection but with different approaches.

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

Usage Guidelines5/5

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

The description provides explicit usage guidance through the 'Application Scenarios' section, listing four specific use cases (e.g., lottery systems, A/B testing). This clearly indicates when to use this tool, though it doesn't explicitly state when not to use it or name alternatives among siblings.

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

Related 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/suxiongye/random-web3-mcp'

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