Skip to main content
Glama
duke0317

Image Processing MCP Server

by duke0317

create_thumbnail_grid

Arrange multiple images into a thumbnail grid with customizable size, columns, spacing, and background for organized visual previews.

Instructions

创建缩略图网格

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
image_sourcesYes图片源列表,每个元素可以是文件路径或base64编码的图片数据
thumbnail_sizeNo缩略图大小(像素)
grid_columnsNo网格列数
spacingNo图片间距(像素)
background_colorNo背景颜色,支持十六进制颜色代码#FFFFFF
output_formatNo输出格式:PNG、JPEG、WEBP 等PNG

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The core asynchronous function implementing the thumbnail grid creation logic: validates inputs, generates square thumbnails with optional borders, arranges them in a grid layout, and returns base64 output.
    async def create_thumbnail_grid(arguments: Dict[str, Any]) -> List[TextContent]:
        """
        创建缩略图网格
        
        Args:
            arguments: 包含图片源列表和网格参数的字典
            
        Returns:
            List[TextContent]: 处理结果
        """
        try:
            # 参数验证
            image_sources = arguments.get("image_sources", [])
            if not image_sources:
                raise ValidationError("image_sources不能为空")
            
            thumbnail_size = arguments.get("thumbnail_size", 150)
            columns = arguments.get("columns", 4)
            spacing = arguments.get("spacing", 10)
            background_color = arguments.get("background_color", "#FFFFFF")
            border_width = arguments.get("border_width", 2)
            border_color = arguments.get("border_color", "#CCCCCC")
            output_format = arguments.get("output_format", DEFAULT_IMAGE_FORMAT)
            
            # 验证参数
            validate_numeric_range(thumbnail_size, 50, 300, "thumbnail_size")
            validate_numeric_range(columns, 1, 10, "columns")
            validate_numeric_range(spacing, 0, 50, "spacing")
            validate_color_hex(background_color)
            validate_numeric_range(border_width, 0, 10, "border_width")
            validate_color_hex(border_color)
            
            processor = ImageProcessor()
            thumbnails = []
            
            # 创建缩略图
            for source in image_sources:
                try:
                    ensure_valid_image_source(source)
                    image = processor.load_image(source)
                    
                    # 创建正方形缩略图
                    image.thumbnail((thumbnail_size, thumbnail_size), Image.Resampling.LANCZOS)
                    
                    # 创建正方形背景
                    thumb = Image.new("RGB", (thumbnail_size, thumbnail_size), background_color)
                    
                    # 居中粘贴图片
                    x_offset = (thumbnail_size - image.width) // 2
                    y_offset = (thumbnail_size - image.height) // 2
                    thumb.paste(image, (x_offset, y_offset))
                    
                    # 添加边框
                    if border_width > 0:
                        draw = ImageDraw.Draw(thumb)
                        for i in range(border_width):
                            draw.rectangle(
                                [i, i, thumbnail_size - 1 - i, thumbnail_size - 1 - i],
                                outline=border_color
                            )
                    
                    thumbnails.append(thumb)
                    
                except Exception as e:
                    # 创建错误占位符
                    error_thumb = Image.new("RGB", (thumbnail_size, thumbnail_size), "#FF0000")
                    draw = ImageDraw.Draw(error_thumb)
                    draw.text((10, thumbnail_size//2), "ERROR", fill="white")
                    thumbnails.append(error_thumb)
            
            # 计算网格尺寸
            rows = (len(thumbnails) + columns - 1) // columns
            grid_width = columns * thumbnail_size + spacing * (columns - 1)
            grid_height = rows * thumbnail_size + spacing * (rows - 1)
            
            # 创建网格
            grid = Image.new("RGB", (grid_width, grid_height), background_color)
            
            for i, thumb in enumerate(thumbnails):
                row = i // columns
                col = i % columns
                
                x = col * (thumbnail_size + spacing)
                y = row * (thumbnail_size + spacing)
                
                grid.paste(thumb, (x, y))
            
            # 转换为base64
            output_info = processor.output_image(grid, "batch_resize", output_format)
            
            return [TextContent(
                type="text",
                text=json.dumps({
                    "success": True,
                    "message": f"成功创建{len(thumbnails)}个缩略图的网格",
                    "data": {
                        **output_info,
                        "metadata": {
                            "thumbnail_count": len(thumbnails),
                            "grid_size": f"{grid.width}x{grid.height}",
                            "thumbnail_size": thumbnail_size,
                            "columns": columns,
                            "rows": rows,
                            "spacing": spacing,
                            "border_width": border_width,
                            "format": output_format
                        }
                    }
                }, ensure_ascii=False)
            )]
            
        except ValidationError as e:
            return [TextContent(
                type="text",
                text=json.dumps({
                    "success": False,
                    "error": f"参数验证失败: {str(e)}"
                }, ensure_ascii=False)
            )]
        except Exception as e:
            return [TextContent(
                type="text",
                text=json.dumps({
                    "success": False,
                    "error": f"创建缩略图网格失败: {str(e)}"
                }, ensure_ascii=False)
            )]
  • Input schema definition for the create_thumbnail_grid tool, specifying parameters like image_sources, thumbnail_size, columns, spacing, colors, etc., with validation constraints.
    Tool(
        name="create_thumbnail_grid",
        description="创建缩略图网格",
        inputSchema={
            "type": "object",
            "properties": {
                "image_sources": {
                    "type": "array",
                    "description": "图片源列表(文件路径或base64编码)",
                    "items": {"type": "string"},
                    "minItems": 1,
                    "maxItems": 20
                },
                "thumbnail_size": {
                    "type": "integer",
                    "description": "缩略图大小(像素)",
                    "minimum": 50,
                    "maximum": 300,
                    "default": 150
                },
                "columns": {
                    "type": "integer",
                    "description": "列数",
                    "minimum": 1,
                    "maximum": 10,
                    "default": 4
                },
                "spacing": {
                    "type": "integer",
                    "description": "间距(像素)",
                    "minimum": 0,
                    "maximum": 50,
                    "default": 10
                },
                "background_color": {
                    "type": "string",
                    "description": "背景颜色(十六进制格式)",
                    "default": "#FFFFFF"
                },
                "border_width": {
                    "type": "integer",
                    "description": "边框宽度",
                    "minimum": 0,
                    "maximum": 10,
                    "default": 2
                },
                "border_color": {
                    "type": "string",
                    "description": "边框颜色(十六进制格式)",
                    "default": "#CCCCCC"
                },
                "output_format": {
                    "type": "string",
                    "description": "输出格式",
                    "enum": ["PNG", "JPEG", "WEBP"],
                    "default": "PNG"
                }
            },
            "required": ["image_sources"]
        }
    ),
  • main.py:699-724 (registration)
    FastMCP tool registration using @mcp.tool() decorator. Defines input parameters with Pydantic validation and wraps the call to the advanced handler function.
    @mcp.tool()
    def create_thumbnail_grid(
        image_sources: Annotated[list, Field(description="图片源列表,每个元素可以是文件路径或base64编码的图片数据")],
        thumbnail_size: Annotated[int, Field(description="缩略图大小(像素)", ge=50, default=150)],
        grid_columns: Annotated[int, Field(description="网格列数", ge=1, default=4)],
        spacing: Annotated[int, Field(description="图片间距(像素)", ge=0, default=10)],
        background_color: Annotated[str, Field(description="背景颜色,支持十六进制颜色代码", default="#FFFFFF")],
        output_format: Annotated[str, Field(description="输出格式:PNG、JPEG、WEBP 等", default="PNG")]
    ) -> str:
        """创建缩略图网格"""
        try:
            arguments = {
                "image_sources": image_sources,
                "thumbnail_size": thumbnail_size,
                "grid_columns": grid_columns,
                "spacing": spacing,
                "background_color": background_color,
                "output_format": output_format
            }
            result = safe_run_async(advanced_create_thumbnail_grid(arguments))
            return result[0].text
        except Exception as e:
            return json.dumps({
                "success": False,
                "error": f"创建缩略图网格失败: {str(e)}"
            }, ensure_ascii=False, indent=2)
Behavior1/5

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

With no annotations provided, the description carries full burden for behavioral disclosure but provides none. It doesn't indicate whether this is a read-only or destructive operation, what permissions might be needed, what happens with invalid inputs, or any rate limits. The description doesn't even mention that this tool outputs an image file, though the output schema would reveal this.

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

Conciseness2/5

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

While technically concise with just three Chinese characters, this is under-specification rather than effective conciseness. The single phrase doesn't provide enough information to be helpful. Every sentence should earn its place, but here the single phrase doesn't earn its place by providing meaningful guidance.

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

Completeness2/5

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

Given the tool's complexity (6 parameters, image processing operation) and lack of annotations, the description is inadequate. While an output schema exists (which would reveal the return type), the description doesn't provide the minimal context needed for an agent to understand when and why to use this tool versus alternatives. For a tool with multiple parameters and sibling alternatives, this description is incomplete.

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?

Schema description coverage is 100%, so the schema already fully documents all 6 parameters. The description adds no additional parameter information beyond what's in the schema. According to scoring rules, when schema coverage is high (>80%), the baseline is 3 even with no param info in the description.

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

Purpose2/5

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

The description '创建缩略图网格' (Create thumbnail grid) is a tautology that restates the tool name in Chinese without adding specificity. It doesn't distinguish this tool from sibling tools like 'create_collage' or 'create_gif' that also create composite images. While the verb 'create' and resource 'thumbnail grid' are present, the description lacks details about what makes this tool unique.

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

Usage Guidelines1/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. With multiple sibling tools for image composition (create_collage, create_gif, create_polaroid), there's no indication of when a thumbnail grid is appropriate versus other formats. No prerequisites, exclusions, or comparison to other tools are mentioned.

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/duke0317/ps-mcp'

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