Skip to main content
Glama
duke0317

Image Processing MCP Server

by duke0317

save_image

Save processed images to specified file paths with customizable format and quality settings for organized storage and output management.

Instructions

保存图片到指定路径

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
image_sourceYes图片源,可以是文件路径或base64编码的图片数据
output_pathYes输出文件路径,包含文件名和扩展名(如 'output.png')
formatNo图片格式,支持 PNG、JPEG、WEBP、BMP、TIFF 等PNG
qualityNo图片质量,范围 1-100,仅对 JPEG 格式有效

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • main.py:122-137 (registration)
    Registers the 'save_image' MCP tool using @mcp.tool() decorator. Defines input schema via Annotated parameters with Field descriptions. Delegates execution to basic_save_image from tools.basic.
    def save_image(
        image_source: Annotated[str, Field(description="图片源,可以是文件路径或base64编码的图片数据")],
        output_path: Annotated[str, Field(description="输出文件路径,包含文件名和扩展名(如 'output.png')")],
        format: Annotated[str, Field(description="图片格式,支持 PNG、JPEG、WEBP、BMP、TIFF 等", default="PNG")],
        quality: Annotated[int, Field(description="图片质量,范围 1-100,仅对 JPEG 格式有效", ge=1, le=100, default=95)]
    ) -> str:
        """保存图片到指定路径"""
        try:
            result = safe_run_async(basic_save_image(image_source, output_path, format, quality))
            return result[0].text
        except Exception as e:
            return json.dumps({
                "success": False,
                "error": f"保存图片失败: {str(e)}"
            }, ensure_ascii=False, indent=2)
  • Core handler function for save_image tool. Validates parameters, loads image from base64 data using ImageProcessor, saves the image to output_path, computes file size, and returns JSON result.
    async def save_image(image_data: str, output_path: str, format: str = "PNG", quality: int = 95) -> list[TextContent]:
        """
        保存图片到指定路径
        
        Args:
            image_data: 图片数据(base64编码)
            output_path: 输出文件路径
            format: 图片格式
            quality: 图片质量
            
        Returns:
            保存结果响应
        """
        try:
            # 验证参数
            if not image_data or not output_path:
                raise ValidationError("图片数据和输出路径不能为空")
            
            if not validate_image_format(format):
                raise ValidationError(f"不支持的图片格式: {format}")
            
            if not (1 <= quality <= 100):
                raise ValidationError("图片质量必须在1-100之间")
            
            # 加载图片
            image = processor.load_image(image_data)
            
            # 保存图片
            saved_path = processor.save_image(image, output_path, format, quality)
            
            # 获取文件信息
            file_size = os.path.getsize(saved_path)
            
            result = {
                "success": True,
                "message": "图片保存成功",
                "data": {
                    "output_path": saved_path,
                    "format": format,
                    "file_size": file_size,
                    "quality": quality
                }
            }
            
            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))]
  • Low-level helper method in ImageProcessor class that performs the actual PIL Image saving to disk, handling JPEG transparency conversion and directory creation.
    def save_image(self, image: Image.Image, output_path: str, 
                   format: str = 'PNG', quality: int = 95) -> str:
        """
        保存图片到指定路径
        
        Args:
            image: PIL Image对象
            output_path: 输出文件路径
            format: 图片格式
            quality: 图片质量 (1-100)
            
        Returns:
            保存的文件路径
        """
        try:
            # 确保输出目录存在
            os.makedirs(os.path.dirname(output_path), exist_ok=True)
            
            # 保存图片
            if format.upper() == 'JPEG':
                # JPEG不支持透明度,需要转换
                if image.mode in ('RGBA', 'LA'):
                    background = Image.new('RGB', image.size, (255, 255, 255))
                    background.paste(image, mask=image.split()[-1] if image.mode == 'RGBA' else None)
                    image = background
                image.save(output_path, format=format, quality=quality)
            else:
                image.save(output_path, format=format)
            
            return output_path
            
        except Exception as e:
            raise IOError(f"图片保存失败: {str(e)}")
  • Input schema definition for save_image tool in the get_basic_tools() function (potentially unused as main.py uses Annotated schema).
    Tool(
        name="save_image",
        description="保存图片到指定路径",
        inputSchema={
            "type": "object",
            "properties": {
                "image_data": {
                    "type": "string",
                    "description": "图片数据(base64编码)"
                },
                "output_path": {
                    "type": "string",
                    "description": "输出文件路径"
                },
                "format": {
                    "type": "string",
                    "description": "图片格式(PNG, JPEG, BMP等)",
                    "default": "PNG"
                },
                "quality": {
                    "type": "integer",
                    "description": "图片质量(1-100,仅对JPEG有效)",
                    "minimum": 1,
                    "maximum": 100,
                    "default": 95
                }
            },
            "required": ["image_data", "output_path"]
        }
Behavior2/5

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

No annotations are provided, so the description carries full burden. It states the action ('save') but lacks critical behavioral details: it doesn't specify if the tool overwrites existing files, requires write permissions, handles errors (e.g., invalid paths), or has performance implications. For a write operation with zero annotation coverage, this is a significant gap in transparency.

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, efficient sentence in Chinese ('保存图片到指定路径') that directly states the tool's purpose with zero waste. It's front-loaded and appropriately sized for a straightforward save operation, earning full marks for conciseness.

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's moderate complexity (4 parameters, write operation) and rich schema (100% coverage, output schema exists), the description is minimally adequate. It states the core purpose but lacks behavioral context (e.g., file overwriting, error handling) and usage guidelines. The output schema reduces the need to explain return values, but for a mutation tool with no annotations, more completeness is warranted.

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 fully documents all parameters (image_source, output_path, format, quality). The description adds no additional parameter semantics beyond what's in the schema. Baseline 3 is appropriate when the schema does all the heavy lifting, but the description doesn't compensate or enhance understanding.

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 '保存图片到指定路径' (Save image to specified path) clearly states the action (save) and resource (image), making the purpose immediately understandable. It distinguishes from sibling tools like 'load_image' or 'convert_format' by focusing on saving rather than loading or converting. However, it doesn't explicitly differentiate from all siblings (e.g., 'create_gif' also saves output).

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 prerequisites (e.g., needing an image source first), compare to similar tools like 'convert_format' (which might also save), or specify use cases (e.g., for final output vs. intermediate processing). Usage is implied but not articulated.

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