secure_token_hex
Generate a cryptographically secure random hex token for authentication and security purposes. Specify the number of bytes to control length.
Instructions
Generate a secure random hex token.
Args: nbytes: Number of random bytes to generate (default 32)
Returns: Hex string containing 2*nbytes characters
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| nbytes | No |
Output Schema
| Name | Required | Description | Default |
|---|---|---|---|
| result | Yes |
Implementation Reference
- src/random_number_mcp/tools.py:122-136 (handler)The actual implementation of secure_token_hex. Uses secrets.token_hex to generate a cryptographically secure random hex string. Validates nbytes via validate_positive_int (must be int >= 0), then calls secrets.token_hex.
def secure_token_hex(nbytes: int = 32) -> str: """Generate a secure random hex token. Args: nbytes: Number of random bytes to generate (default 32) Returns: Hex string containing 2*nbytes characters Raises: ValueError: If nbytes < 0 TypeError: If nbytes is not an integer """ validate_positive_int(nbytes, "nbytes") return secrets.token_hex(nbytes) - src/random_number_mcp/server.py:99-109 (registration)The MCP tool decorator (@app.tool()) that registers secure_token_hex as a callable tool. It delegates to tools.secure_token_hex.
@app.tool() def secure_token_hex(nbytes: int = 32) -> str: """Generate a secure random hex token. Args: nbytes: Number of random bytes to generate (default 32) Returns: Hex string containing 2*nbytes characters """ return tools.secure_token_hex(nbytes) - src/random_number_mcp/utils.py:12-17 (helper)The validate_positive_int helper used by secure_token_hex to ensure nbytes 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}") - Input/output schema is defined by the function signature: nbytes: int = 32 (input) -> str (output). The docstring specifies the return value is a hex string of 2*nbytes characters.
def secure_token_hex(nbytes: int = 32) -> str: """Generate a secure random hex token. Args: nbytes: Number of random bytes to generate (default 32) Returns: Hex string containing 2*nbytes characters Raises: ValueError: If nbytes < 0 TypeError: If nbytes is not an integer """ validate_positive_int(nbytes, "nbytes") return secrets.token_hex(nbytes)