Skip to main content
Glama
duke0317

Image Processing MCP Server

by duke0317

resize_image

Resize images to specific dimensions while optionally maintaining aspect ratio and selecting resampling algorithms for quality control.

Instructions

调整图片大小

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
image_sourceYes图片源,可以是文件路径或base64编码的图片数据
widthYes目标宽度(像素)
heightYes目标高度(像素)
keep_aspect_ratioNo是否保持宽高比,True时会按比例缩放
resampleNo重采样算法:LANCZOS(高质量)、BILINEAR(平滑)、NEAREST(快速)LANCZOS

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Core handler function that performs the image resizing using PIL, with aspect ratio handling, resampling, validation, and JSON output.
    async def resize_image(image_source: str, width: int, height: int, 
                          keep_aspect_ratio: bool = True, resample: str = "LANCZOS") -> list[TextContent]:
        """
        调整图片大小
        
        Args:
            image_source: 图片源(文件路径或base64编码数据)
            width: 目标宽度
            height: 目标高度
            keep_aspect_ratio: 是否保持宽高比
            resample: 重采样方法
            
        Returns:
            调整后的图片数据
        """
        try:
            # 验证参数
            if not image_source:
                raise ValidationError("图片源不能为空")
            
            ensure_valid_dimensions(width, height)
            
            # 验证重采样方法
            resample_methods = {
                'NEAREST': Image.NEAREST,
                'BILINEAR': Image.BILINEAR,
                'BICUBIC': Image.BICUBIC,
                'LANCZOS': Image.LANCZOS
            }
            
            if resample.upper() not in resample_methods:
                raise ValidationError(f"不支持的重采样方法: {resample}")
            
            # 加载图片
            image = processor.load_image(image_source)
            original_size = image.size
            
            # 计算目标尺寸
            if keep_aspect_ratio:
                # 保持宽高比,计算实际尺寸
                aspect_ratio = original_size[0] / original_size[1]
                target_aspect_ratio = width / height
                
                if aspect_ratio > target_aspect_ratio:
                    # 以宽度为准
                    new_width = width
                    new_height = int(width / aspect_ratio)
                else:
                    # 以高度为准
                    new_height = height
                    new_width = int(height * aspect_ratio)
            else:
                new_width, new_height = width, height
            
            # 调整大小
            resized_image = image.resize(
                (new_width, new_height), 
                resample_methods[resample.upper()]
            )
            
            # 输出调整后的图片
            output_info = processor.output_image(resized_image, f"resize_{new_width}x{new_height}")
            
            result = {
                "success": True,
                "message": f"图片大小调整成功: {original_size} -> {(new_width, new_height)}",
                "data": {
                    **output_info,
                    "original_size": original_size,
                    "new_size": (new_width, new_height),
                    "keep_aspect_ratio": keep_aspect_ratio,
                    "resample_method": resample
                }
            }
            
            return [TextContent(type="text", text=json.dumps(result, ensure_ascii=False))]
            
        except ValidationError as e:
            error_result = {
                "success": False,
                "error": f"参数验证失败: {str(e)}"
            }
            return [TextContent(type="text", text=json.dumps(error_result, ensure_ascii=False))]
            
        except Exception as e:
            error_result = {
                "success": False,
                "error": f"图片大小调整失败: {str(e)}"
            }
            return [TextContent(type="text", text=json.dumps(error_result, ensure_ascii=False))]
  • main.py:170-186 (registration)
    MCP tool registration using @mcp.tool() decorator, defines input schema via Annotated fields, and delegates to the core transform_resize_image implementation.
    @mcp.tool()
    def resize_image(
        image_source: Annotated[str, Field(description="图片源,可以是文件路径或base64编码的图片数据")],
        width: Annotated[int, Field(description="目标宽度(像素)", gt=0)],
        height: Annotated[int, Field(description="目标高度(像素)", gt=0)],
        keep_aspect_ratio: Annotated[bool, Field(description="是否保持宽高比,True时会按比例缩放", default=True)],
        resample: Annotated[str, Field(description="重采样算法:LANCZOS(高质量)、BILINEAR(平滑)、NEAREST(快速)", default="LANCZOS")]
    ) -> str:
        """调整图片大小"""
        try:
            result = safe_run_async(transform_resize_image(image_source, width, height, keep_aspect_ratio, resample))
            return result[0].text
        except Exception as e:
            return json.dumps({
                "success": False,
                "error": f"调整图片大小失败: {str(e)}"
            }, ensure_ascii=False, indent=2)
  • Tool schema definition including input schema, properties, constraints, and defaults for resize_image.
    Tool(
        name="resize_image",
        description="调整图片大小",
        inputSchema={
            "type": "object",
            "properties": {
                "image_data": {
                    "type": "string",
                    "description": "图片数据(base64编码)"
                },
                "width": {
                    "type": "integer",
                    "description": "目标宽度",
                    "minimum": 1,
                    "maximum": 4096
                },
                "height": {
                    "type": "integer",
                    "description": "目标高度",
                    "minimum": 1,
                    "maximum": 4096
                },
                "keep_aspect_ratio": {
                    "type": "boolean",
                    "description": "是否保持宽高比",
                    "default": True
                },
                "resample": {
                    "type": "string",
                    "description": "重采样方法(NEAREST, BILINEAR, BICUBIC, LANCZOS)",
                    "default": "LANCZOS"
                }
            },
            "required": ["image_data", "width", "height"]
        }
    ),
Behavior2/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. '调整图片大小' only states the basic function without mentioning whether this modifies the original image, creates a new file, what formats are supported, performance characteristics, or error conditions. It lacks crucial context about what actually happens during the resize operation.

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 maximally concise with just three Chinese characters that directly convey the core function. There's zero wasted text, and it's perfectly front-loaded with the essential information.

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 the tool has an output schema and 100% schema description coverage, the description doesn't need to explain return values or parameters. However, as a mutation tool with no annotations, it should provide more behavioral context about what the operation actually does (creates new file, modifies in-place, supported formats, etc.). The presence of output schema helps but doesn't fully compensate for the lack of operational transparency.

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 documents all 5 parameters thoroughly. The description adds no additional parameter information beyond what's in the schema. The baseline score of 3 reflects adequate parameter documentation through the schema alone.

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 '调整图片大小' (resize image) clearly states the verb and resource. It distinguishes from siblings like 'crop_image', 'rotate_image', or 'batch_resize' by focusing specifically on resizing. However, it doesn't explicitly differentiate from 'create_thumbnail_grid' which might involve resizing as part of its operation.

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. It doesn't mention when resizing is appropriate compared to cropping, rotating, or using batch operations. There's no context about prerequisites, limitations, or typical use cases.

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