Skip to main content
Glama

generate_password

Read-only

Generate a random password of specified length between 8 and 64 characters, with optional inclusion of special characters for enhanced security.

Instructions

Generate a random password with specified length, optionally including special characters.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
lengthNoThe length of the password to generate (between 8 and 64 characters).
use_special_charsNoInclude special characters in the password.

Implementation Reference

  • The 'generate_password' async method that implements password generation: generates a random password with configurable length (8-64) and optional special characters, ensuring complexity requirements (lowercase, uppercase, >=2 digits, and optionally special chars) via iterative generation.
    async def generate_password(
        self,
        ctx: Context,
        length: Annotated[
            int,
            Field(
                default=12,
                ge=8,
                le=64,
                description="The length of the password to generate (between 8 and 64 characters).",
            ),
        ] = 12,
        use_special_chars: Annotated[
            bool,
            Field(
                default=False,
                description="Include special characters in the password.",
            ),
        ] = False,
    ) -> ToolResult:
        """Generate a random password with specified length, optionally including special characters."""
        """The password will meet the complexity requirements of at least one lowercase letter, one uppercase letter, and two digits.
        If special characters are included, it will also contain at least one such character.
        Until the password meets these requirements, it will keep regenerating.
        This is a simple example of a tool that can be used to generate passwords. It is not intended for production use."""
        characters = string.ascii_letters + string.digits
        if use_special_chars:
            characters += string.punctuation
        password_generation_attempts = 0
        while True:
            password = "".join(secrets.choice(characters) for _ in range(length))
            password_generation_attempts += 1
            if (
                any(c.islower() for c in password)
                and any(c.isupper() for c in password)
                and sum(c.isdigit() for c in password) >= 2
                and (not use_special_chars or any(c in string.punctuation for c in password))
            ):
                await ctx.info("Generated password meets complexity requirements.")
                break
            else:
                # Exclude from coverage because this may not always happen in tests
                await ctx.warning(  # pragma: no cover
                    f"Re-generating since the generated password did not meet complexity requirements: {password}"
                )
        return self.get_tool_result(
            result=password,
            metadata={
                "generate_password": {
                    "length_satisfied": len(password) == length,
                    "character_set": characters,
                    "generation_attempts": password_generation_attempts,
                }
            },
        )
  • Input schema for generate_password: 'length' (int, 8-64, default 12) and 'use_special_chars' (bool, default False) using Pydantic Field annotations.
    async def generate_password(
        self,
        ctx: Context,
        length: Annotated[
            int,
            Field(
                default=12,
                ge=8,
                le=64,
                description="The length of the password to generate (between 8 and 64 characters).",
            ),
        ] = 12,
        use_special_chars: Annotated[
            bool,
            Field(
                default=False,
                description="Include special characters in the password.",
            ),
        ] = False,
    ) -> ToolResult:
  • Tool registration entry listing 'generate_password' with tags and annotations in the PyMCP class tools list.
    {
        "fn": "generate_password",
        "tags": ["password-generation", "example"],
        "annotations": {"readOnlyHint": True},
    },
  • Generic tool registration logic in MCPMixin.register_features: iterates over self.tools, extracts 'fn' name, and registers the corresponding method with FastMCP using mcp.tool().
    # Register tools
    for tool in self.tools:
        assert "fn" in tool, "Tool metadata must include the 'fn' key."
        tool_copy = copy.deepcopy(tool)
        fn_name = tool_copy.pop("fn")
        fn = getattr(self, fn_name)
        mcp.tool(**tool_copy)(fn)  # pass remaining metadata as kwargs
  • get_tool_result helper used by generate_password to create a ToolResult with structured_content and metadata.
    def get_tool_result(self, result: Any, metadata: dict[str, Any] | None = None) -> ToolResult:  # pragma: no cover
        """Create a ToolResult object with the given result and metadata, including package metadata.
    
        Args:
            result (Any): The result to include in the ToolResult.
            metadata (Dict[str, Any] | None, optional): Additional metadata to include. Defaults to None.
    
        Returns:
            ToolResult: The ToolResult object containing the result and metadata.
        """
        return ToolResult(
            structured_content={"result": result} if not isinstance(result, dict) else result,
            meta=metadata if metadata is not None else None,
        )
Behavior3/5

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

Annotations already declare readOnlyHint=true, indicating no side effects. The description adds that the password is random and optionally includes special characters, but does not elaborate on randomness source or security properties. This is adequate given the annotation coverage.

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 a single, front-loaded sentence with no unnecessary words. Every word contributes to understanding the tool's purpose and parameters.

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?

For a simple two-parameter tool with annotations, the description covers the essential functionality. It does not explain the character set or security guarantees, but these are not critical for basic usage.

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

Parameters3/5

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

Input schema coverage is 100%, with each parameter fully described (length: min/max/default; use_special_chars: boolean/default). The description adds no additional meaning beyond paraphrasing the boolean parameter.

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 verb 'generate' and the resource 'random password', and it specifies the controllable parameters (length and special characters). There are no similar sibling tools, so no differentiation needed.

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

Usage Guidelines4/5

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

The description implies usage for generating passwords, but does not explicitly mention when to use it versus alternatives. However, given that no similar tools exist on the server, the lack of explicit guidance is acceptable.

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/anirbanbasu/pymcp'

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