Skip to main content
Glama
sanliunanjue

Image Processor MCP Server

by sanliunanjue

process_image_to_code

Convert images to functional code by analyzing visual content and generating programming language output based on specified requirements.

Instructions

处理图像并生成代码

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
image_urlYes图像URL
languageNo目标编程语言,例如:python, javascript, html, css等python
instructionsNo额外的指令或要求

Implementation Reference

  • Main execution handler for the 'process_image_to_code' tool. Downloads image from provided URL, constructs a Chinese prompt for generating code in the specified language (default Python), calls the Qwen VL model via processImageWithQwen helper, and returns the generated code or an error message.
    case "process_image_to_code": {
      const imageUrl = String(request.params.arguments?.image_url);
      const language = String(request.params.arguments?.language || "python");
      const instructions = String(request.params.arguments?.instructions || "");
      
      if (!imageUrl) {
        throw new Error("图像URL是必需的");
      }
      
      try {
        // 下载图像
        const imagePath = await downloadImage(imageUrl);
        
        // 构建提示词
        let prompt = `请根据这张图片生成${language}代码。`;
        if (instructions) {
          prompt += ` ${instructions}`;
        }
        
        // 处理图像
        const result = await processImageWithQwen(imagePath, prompt);
        
        return {
          content: [{
            type: "text",
            text: result
          }]
        };
      } catch (error: any) {
        return {
          content: [{
            type: "text",
            text: `处理图像失败: ${error.message}`
          }],
          isError: true
        };
      }
    }
  • src/index.ts:155-177 (registration)
    Tool registration in the ListTools handler, defining name, description, and full input schema including required image_url, optional language (default 'python'), and instructions.
      name: "process_image_to_code",
      description: "处理图像并生成代码",
      inputSchema: {
        type: "object",
        properties: {
          image_url: {
            type: "string",
            description: "图像URL"
          },
          language: {
            type: "string",
            description: "目标编程语言,例如:python, javascript, html, css等",
            default: "python"
          },
          instructions: {
            type: "string",
            description: "额外的指令或要求",
            default: ""
          }
        },
        required: ["image_url"]
      }
    },
  • Core helper function that encodes the local image file to base64, constructs the API request payload for Qwen-VL-Plus model with user message containing text prompt and image, calls the Dashscope API, extracts the output text, handles errors, and deletes the temp image file.
    async function processImageWithQwen(imagePath: string, prompt: string): Promise<string> {
      try {
        // 读取图像文件
        const imageBuffer = fs.readFileSync(imagePath);
        const base64Image = imageBuffer.toString('base64');
        
        // 准备请求数据
        const requestData = {
          model: "qwen-vl-plus",
          input: {
            messages: [
              {
                role: "user",
                content: [
                  {
                    type: "text",
                    text: prompt
                  },
                  {
                    type: "image",
                    image: base64Image
                  }
                ]
              }
            ]
          },
          parameters: {}
        };
        
        // 发送请求到API
        const response = await axios.post(API_ENDPOINT, requestData, {
          headers: {
            'Authorization': `Bearer ${API_KEY}`,
            'Content-Type': 'application/json'
          }
        });
        
        // 处理响应
        if (response.data && response.data.output && response.data.output.text) {
          return response.data.output.text;
        } else {
          throw new Error("API响应格式不正确");
        }
      } catch (error: any) {
        console.error("调用qwen2.5-vl模型API失败:", error);
        if (error.response) {
          console.error("API响应:", error.response.data);
        }
        throw new Error(`处理图像失败: ${error.message}`);
      } finally {
        // 清理临时文件
        try {
          fs.unlinkSync(imagePath);
        } catch (e) {
          console.error("清理临时文件失败:", e);
        }
      }
    }
  • Supporting helper to stream-download the image from the provided URL to a uniquely-named temporary JPG file in the system's temp directory.
    async function downloadImage(imageUrl: string): Promise<string> {
      try {
        // 为图像生成唯一文件名
        const filename = `${Date.now()}-${Math.random().toString(36).substring(2, 15)}.jpg`;
        const filePath = path.join(TEMP_DIR, filename);
        
        // 下载图像
        const response = await axios({
          method: 'GET',
          url: imageUrl,
          responseType: 'stream'
        });
        
        await streamPipeline(response.data, fs.createWriteStream(filePath));
        return filePath;
      } catch (error: any) {
        console.error("下载图像失败:", error);
        throw new Error(`下载图像失败: ${error.message}`);
      }
    }
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It states the tool processes images and generates code, but doesn't explain how it handles different image types, what the output format is (e.g., code snippet, full file), error handling, or any limitations (e.g., image size, supported languages beyond the schema). This leaves significant gaps in understanding the tool's behavior.

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 extremely concise with a single sentence '处理图像并生成代码' that directly states the tool's function. It's front-loaded with no wasted words, making it efficient and easy to parse. Every word earns its place by conveying essential information.

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 complexity of image-to-code conversion, no annotations, and no output schema, the description is insufficiently complete. It doesn't address what the output looks like (e.g., code structure, error messages), how it handles ambiguous images, or any prerequisites (e.g., image format requirements). For a tool with three parameters and no structured output documentation, more context is needed.

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 schema description coverage is 100%, with clear descriptions for all three parameters in the input schema. The description doesn't add any additional meaning beyond what's already documented in the schema (e.g., it doesn't explain how 'instructions' modify code generation or provide examples). Given the high schema coverage, the baseline score of 3 is appropriate as the schema does the heavy lifting.

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 '处理图像并生成代码' clearly states the tool's purpose: processing images and generating code. It specifies both the verb ('处理' - process) and resource ('图像' - image) with the output ('代码' - code). However, it doesn't differentiate from its sibling 'process_image_to_description', which suggests a similar input but different output type.

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. There's no mention of the sibling tool 'process_image_to_description' or any context about when code generation is preferred over description generation. It lacks explicit usage scenarios or exclusions.

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/sanliunanjue/image-processor-mcp'

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