Skip to main content
Glama

generate_qr_code

Convert text to QR code images with customizable size, border, and colors for easy sharing and scanning.

Instructions

Generate QR code(生成二维码图片) from text and return as image with description.

Args:
    text: Text content to convert to QR code
    box_size: Size of each box in pixels (1-50)
    border: Number of boxes for border (0-20)
    fill_color: Foreground color
    back_color: Background color

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
textYes
box_sizeNo
borderNo
fill_colorNoblack
back_colorNowhite

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
dataYes
typeYes
_metaNo
mimeTypeYes
annotationsNo

Implementation Reference

  • The main handler function for the 'generate_qr_code' tool, decorated with @mcp.tool(), performs input validation and delegates QR code generation to the helper function, returning MCP ImageContent.
    @mcp.tool()
    async def generate_qr_code(
        text: str,
        box_size: int = 10,
        border: int = 4,
        fill_color: str = "black",
        back_color: str = "white",
    ) -> ImageContent:
        """Generate QR code(生成二维码图片) from text and return as image with description.
    
        Args:
            text: Text content to convert to QR code
            box_size: Size of each box in pixels (1-50)
            border: Number of boxes for border (0-20)
            fill_color: Foreground color
            back_color: Background color
        """
        if not text or not text.strip():
            raise ValueError("Text content cannot be empty")
    
        # 验证参数范围
        if not (1 <= box_size <= 50):
            raise ValueError("box_size must be between 1 and 50")
    
        if not (0 <= border <= 20):
            raise ValueError("border must be between 0 and 20")
    
        try:
            # 生成QR码的base64编码
            base64_result = text_to_qr_base64(
                text=text,
                box_size=box_size,
                border=border,
                fill_color=fill_color,
                back_color=back_color,
                image_format="JPEG",
            )
    
            # 按照MCP文档要求的格式返回图片
            return ImageContent(type="image", data=base64_result, mimeType="image/jpeg")
    
        except Exception as e:
            logger.error(f"Failed to generate QR code: {e}")
            raise RuntimeError(f"Failed to generate QR code: {str(e)}")
  • Helper utility function that implements the core QR code generation logic using the qrcode library, producing a base64-encoded image string.
    def text_to_qr_base64(
        text: str,
        error_correction: int = qrcode.constants.ERROR_CORRECT_M,
        box_size: int = 10,
        border: int = 4,
        fill_color: str = "black",
        back_color: str = "white",
        image_format: str = "PNG",
    ) -> str:
        """
        将输入的字符串转换成QR码图片,并返回base64编码的字符串
    
        Args:
            text (str): 要转换的文本内容
            error_correction (int): 错误纠正级别,默认为中等级别
            box_size (int): 每个方块的像素大小,默认为10
            border (int): 边框的方块数量,默认为4
            fill_color (str): 前景色,默认为黑色
            back_color (str): 背景色,默认为白色
            image_format (str): 图片格式,默认为PNG
    
        Returns:
            str: base64编码的图片字符串
    
        Raises:
            ValueError: 当输入文本为空时
            Exception: 其他处理异常
        """
        if not text or not text.strip():
            raise ValueError("输入文本不能为空")
    
        try:
            # 创建QR码实例
            qr = qrcode.QRCode(
                version=1,  # 控制QR码的大小,1是最小的
                error_correction=error_correction,
                box_size=box_size,
                border=border,
            )
    
            # 添加数据
            qr.add_data(text)
            qr.make(fit=True)
    
            # 创建图片
            img = qr.make_image(fill_color=fill_color, back_color=back_color)
    
            # 将图片转换为字节流
            img_buffer = io.BytesIO()
            img.save(img_buffer, format=image_format)
            img_buffer.seek(0)
    
            # 转换为base64
            img_base64 = base64.b64encode(img_buffer.getvalue()).decode("utf-8")
    
            return img_base64
    
        except Exception as e:
            raise Exception(f"生成QR码时发生错误: {str(e)}")
  • The @mcp.tool() decorator registers the generate_qr_code function as an MCP tool.
    @mcp.tool()
  • Type hints and default values define the input schema for the tool parameters, with return type ImageContent.
    async def generate_qr_code(
        text: str,
        box_size: int = 10,
        border: int = 4,
        fill_color: str = "black",
        back_color: str = "white",
    ) -> ImageContent:
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. While it mentions the tool returns an image with description, it doesn't cover important behavioral aspects like error conditions, performance characteristics, rate limits, or authentication requirements. The description is minimal and lacks behavioral context beyond basic functionality.

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 a clear purpose statement followed by organized parameter documentation. It's appropriately sized for a 5-parameter tool. The bilingual text (English/Chinese) adds slight redundancy but doesn't significantly impact conciseness. Every sentence serves a purpose.

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?

Given that there's an output schema (though not provided in the context), the description doesn't need to explain return values. However, for a tool with 5 parameters and no annotations, the description should provide more behavioral context and usage guidance. The parameter documentation is good, but overall completeness is only adequate with clear gaps in behavioral transparency.

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 provides detailed parameter information in the 'Args' section, explaining each parameter's purpose and constraints (e.g., 'Size of each box in pixels (1-50)'). Since schema description coverage is 0%, this information is crucial and adds significant value beyond the bare schema. The only minor gap is that it doesn't explain parameter interactions or provide examples.

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: 'Generate QR code from text and return as image with description.' It specifies the verb (generate), resource (QR code), and output format (image with description). However, since there are no sibling tools, it doesn't need to differentiate from alternatives, so it can't achieve a perfect 5.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives, prerequisites, or typical use cases. It simply states what the tool does without context about when it's appropriate. With no sibling tools, this is less critical, but still a gap in usage guidance.

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/2niuhe/qrcode_mcp'

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