Skip to main content
Glama
duke0317

Image Processing MCP Server

by duke0317

get_image_info

Extract basic image metadata such as dimensions, format, and size from file paths or base64 encoded data to analyze and verify image properties.

Instructions

获取图片基本信息

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
image_sourceYes图片源,可以是文件路径或base64编码的图片数据

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Core asynchronous handler function that implements the get_image_info tool logic: validates input, loads image using ImageProcessor, retrieves basic info, computes extended metrics (data size, aspect ratio, pixels, file info), and returns formatted JSON response.
    async def get_image_info(image_source: str) -> list[TextContent]:
        """
        获取图片信息
        
        Args:
            image_source: 图片源(文件路径或base64编码数据)
            
        Returns:
            图片信息响应
        """
        try:
            # 验证参数
            if not image_source:
                raise ValidationError("图片源不能为空")
            
            # 加载图片
            image = processor.load_image(image_source)
            
            # 获取详细信息
            info = processor.get_image_info(image)
            
            # 计算图片大小(字节)
            import io
            buffer = io.BytesIO()
            image.save(buffer, format=image.format or 'PNG')
            data_size = len(buffer.getvalue())
            
            # 扩展信息
            extended_info = {
                **info,
                "data_size": data_size,
                "aspect_ratio": round(info['width'] / info['height'], 2),
                "total_pixels": info['width'] * info['height']
            }
            
            # 如果是文件路径,添加文件信息
            if not image_source.startswith('data:image') and os.path.exists(image_source):
                extended_info["file_path"] = image_source
                extended_info["file_size_bytes"] = os.path.getsize(image_source)
            
            result = {
                "success": True,
                "message": "获取图片信息成功",
                "data": extended_info
            }
            
            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:138-151 (registration)
    FastMCP tool registration decorator (@mcp.tool()) that defines the public tool interface, calls the core handler via safe_run_async, and handles errors by returning JSON.
    @mcp.tool()
    def get_image_info(
        image_source: Annotated[str, Field(description="图片源,可以是文件路径或base64编码的图片数据")]
    ) -> str:
        """获取图片基本信息"""
        try:
            result = safe_run_async(basic_get_image_info(image_source))
            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 in get_basic_tools() function, specifying input requirements (image_data as base64 string) and description for the get_image_info tool.
    Tool(
        name="get_image_info",
        description="获取图片基本信息",
        inputSchema={
            "type": "object",
            "properties": {
                "image_data": {
                    "type": "string",
                    "description": "图片数据(base64编码)"
                }
            },
            "required": ["image_data"]
        }
    ),
  • Supporting utility method in ImageProcessor class that extracts basic PIL Image properties (size, mode, format, dimensions) used by the main handler.
    def get_image_info(self, image: Image.Image) -> dict:
        """
        获取图片信息
        
        Args:
            image: PIL Image对象
            
        Returns:
            包含图片信息的字典
        """
        return {
            'size': image.size,
            'mode': image.mode,
            'format': image.format,
            'width': image.width,
            'height': image.height
        }
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. It doesn't describe what 'basic information' entails (e.g., dimensions, format, metadata), whether it's a read-only operation, or any performance implications. For a tool with no annotations, 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.

Conciseness4/5

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

The description is a single, efficient phrase in Chinese ('获取图片基本信息'), which is appropriately concise and front-loaded. It wastes no words, though it could benefit from more detail to improve clarity. The structure is minimal but effective for its brevity.

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 low complexity (one parameter) and the presence of an output schema, the description is somewhat complete but lacks depth. It doesn't explain what 'basic information' includes, which is crucial since no annotations are provided. The output schema likely covers return values, but the description should still clarify the tool's scope to aid agent selection.

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?

The input schema has 100% description coverage, clearly documenting the 'image_source' parameter as accepting file paths or base64 data. The description adds no additional parameter semantics beyond what the schema provides. With high schema coverage, the baseline score of 3 is appropriate, as the schema handles the parameter documentation adequately.

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

Purpose3/5

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

The description '获取图片基本信息' (Get basic image information) states a clear purpose with a verb and resource, but it's vague about what 'basic information' includes. It doesn't distinguish from sibling tools like 'extract_colors' or 'get_performance_stats', which might also provide image-related information. The purpose is understandable but lacks specificity.

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?

No guidance is provided on when to use this tool versus alternatives. The description doesn't mention context, prerequisites, or exclusions. Given sibling tools like 'extract_colors' or 'get_performance_stats', there's no indication of how this tool differs in usage, leaving the agent to guess based on the name alone.

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