Skip to main content
Glama
duke0317

Image Processing MCP Server

by duke0317

extract_colors

Extract dominant colors from images to analyze color schemes, identify primary palettes, or process visual data for design and analysis purposes.

Instructions

提取图片主要颜色

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
image_sourceYes图片源,可以是文件路径或base64编码的图片数据
num_colorsNo要提取的主要颜色数量
output_formatNo输出格式:PNG、JPEG、WEBP 等PNG

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The core handler function for the 'extract_colors' tool. It processes the input image by quantizing it to extract the dominant colors, computes RGB and HEX representations, and optionally generates a visual palette image using PIL.
    async def extract_colors(arguments: Dict[str, Any]) -> List[TextContent]:
        """
        提取图片的主要颜色
        
        Args:
            arguments: 包含图片源和颜色提取参数的字典
            
        Returns:
            List[TextContent]: 处理结果
        """
        try:
            # 参数验证
            image_source = arguments.get("image_source")
            ensure_valid_image_source(image_source)
            
            color_count = arguments.get("color_count") or arguments.get("num_colors", 5)
            create_palette = arguments.get("create_palette", True)
            palette_width = arguments.get("palette_width", 400)
            palette_height = arguments.get("palette_height", 100)
            
            # 验证参数
            validate_numeric_range(color_count, 1, 20, "color_count")
            validate_numeric_range(palette_width, 100, 800, "palette_width")
            validate_numeric_range(palette_height, 50, 200, "palette_height")
            
            processor = ImageProcessor()
            image = processor.load_image(image_source)
            
            # 转换为RGB模式
            if image.mode != "RGB":
                image = image.convert("RGB")
            
            # 使用量化来提取主要颜色
            quantized = image.quantize(colors=color_count)
            palette_colors = quantized.getpalette()
            
            # 提取RGB颜色值
            colors = []
            # 确保不超过实际可用的颜色数量
            actual_color_count = min(color_count, len(palette_colors) // 3)
            
            for i in range(actual_color_count):
                try:
                    r = palette_colors[i * 3]
                    g = palette_colors[i * 3 + 1] 
                    b = palette_colors[i * 3 + 2]
                    hex_color = f"#{r:02x}{g:02x}{b:02x}"
                    colors.append({
                        "rgb": [r, g, b],
                        "hex": hex_color
                    })
                except IndexError:
                    # 如果索引越界,停止添加颜色
                    break
            
            result_data = {
                "success": True,
                "message": f"成功提取{len(colors)}种主要颜色",
                "colors": colors,
                "metadata": {
                    "image_size": f"{image.width}x{image.height}",
                    "color_count": len(colors)
                }
            }
            
            # 创建调色板图片
            if create_palette:
                palette_image = Image.new("RGB", (palette_width, palette_height))
                color_width = palette_width // len(colors)
                
                for i, color_info in enumerate(colors):
                    color_rgb = tuple(color_info["rgb"])
                    x1 = i * color_width
                    x2 = (i + 1) * color_width if i < len(colors) - 1 else palette_width
                    
                    # 填充颜色块
                    for x in range(x1, x2):
                        for y in range(palette_height):
                            palette_image.putpixel((x, y), color_rgb)
                
                # 输出调色板图片
                palette_output = processor.output_image(palette_image, "extract_colors", "PNG")
                result_data["palette"] = palette_output
                result_data["metadata"]["palette_size"] = f"{palette_width}x{palette_height}"
            
            return [TextContent(
                type="text",
                text=json.dumps(result_data, 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 'extract_colors' tool, defining parameters like image_source, color_count, and palette options as part of the Tool object in get_advanced_tools().
    Tool(
        name="extract_colors",
        description="提取图片的主要颜色",
        inputSchema={
            "type": "object",
            "properties": {
                "image_source": {
                    "type": "string",
                    "description": "图片源(文件路径或base64编码)"
                },
                "color_count": {
                    "type": "integer",
                    "description": "提取的颜色数量",
                    "minimum": 1,
                    "maximum": 20,
                    "default": 5
                },
                "create_palette": {
                    "type": "boolean",
                    "description": "是否创建调色板图片",
                    "default": True
                },
                "palette_width": {
                    "type": "integer",
                    "description": "调色板宽度",
                    "minimum": 100,
                    "maximum": 800,
                    "default": 400
                },
                "palette_height": {
                    "type": "integer",
                    "description": "调色板高度",
                    "minimum": 50,
                    "maximum": 200,
                    "default": 100
                }
            },
            "required": ["image_source"]
        }
    ),
  • main.py:752-771 (registration)
    MCP tool registration for 'extract_colors' using @mcp.tool() decorator. This wrapper function adapts parameters and calls the advanced handler from tools.advanced.
    def extract_colors(
        image_source: Annotated[str, Field(description="图片源,可以是文件路径或base64编码的图片数据")],
        num_colors: Annotated[int, Field(description="要提取的主要颜色数量", ge=1, le=20, default=5)],
        output_format: Annotated[str, Field(description="输出格式:PNG、JPEG、WEBP 等", default="PNG")]
    ) -> str:
        """提取图片主要颜色"""
        try:
            arguments = {
                "image_source": image_source,
                "num_colors": num_colors,
                "output_format": output_format
            }
            result = safe_run_async(advanced_extract_colors(arguments))
            return result[0].text
        except Exception as e:
            return json.dumps({
                "success": False,
                "error": f"提取颜色失败: {str(e)}"
            }, ensure_ascii=False, indent=2)
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 states what the tool does ('extract main colors') but doesn't describe how it behaves: e.g., whether it returns color codes (like RGB/HEX), how colors are determined (e.g., clustering algorithms), if it modifies the image, or any performance considerations. This leaves gaps for an AI agent to understand the tool's 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 a single, efficient phrase ('提取图片主要颜色') that directly conveys the core function without unnecessary words. It's front-loaded and wastes no space, making it easy for an AI agent to parse quickly.

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 (extracting colors from images), no annotations, and an output schema (which handles return values), the description is minimally adequate. It states the purpose but lacks behavioral details and usage context. With output schema covering returns, the description doesn't need to explain outputs, but it should provide more operational guidance to be fully complete.

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 description adds no parameter-specific information beyond what's in the input schema, which has 100% coverage with clear descriptions for all three parameters (image_source, num_colors, output_format). Since schema coverage is high, the baseline is 3, as the schema adequately documents parameters without needing extra details in the description.

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 '提取图片主要颜色' (Extract main colors from an image) clearly states the verb ('extract') and resource ('main colors from an image'), making the purpose immediately understandable. However, it doesn't explicitly differentiate from sibling tools like 'get_image_info' or 'convert_to_grayscale', which might also involve color analysis, though those have different primary functions.

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), exclusions, or compare it to siblings like 'get_image_info' that might provide color-related data. Usage is implied by the purpose but not explicitly stated.

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