Skip to main content
Glama
lengbone

MCP Visual Language

by lengbone

auto_analyze_image

Analyze images to extract and interpret code, architecture diagrams, errors, or documentation using AI-powered visual recognition. Supports file paths, URLs, or clipboard input.

Instructions

自动获取并分析图片(支持文件路径、网络URL或剪贴板)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
imagePathNo图片文件路径或网络URL(可选,不提供则使用剪贴板)
focusAreaNo分析重点区域code

Implementation Reference

  • Core handler function that automatically acquires image from file path, network URL, or clipboard, processes it with sharp, analyzes using GLMService, and returns structured result including source.
    async autoGetAndAnalyzeImage(
      imagePath?: string,
      focusArea: 'code' | 'architecture' | 'error' | 'documentation' = 'code'
    ): Promise<ImageAnalysisResult & { source: string }> {
      try {
        logger.info('开始自动获取图片', { imagePath, focusArea });
    
        let source: string;
        let finalImagePath: string;
    
        if (imagePath) {
          // 检查是否为网络URL
          if (this.isUrl(imagePath)) {
            source = 'url';
            finalImagePath = await this.downloadImageFromUrl(imagePath);
            logger.info('从网络URL下载图片', { url: imagePath, path: finalImagePath });
          } else {
            // 如果提供了文件路径,直接使用
            source = 'file';
            finalImagePath = imagePath;
    
            // 验证文件是否存在
            if (!(await this.fileExists(finalImagePath))) {
              throw new Error(`文件不存在: ${imagePath}`);
            }
    
            logger.info('使用提供的文件路径', { path: finalImagePath });
          }
        } else {
          // 如果没有提供文件路径,尝试从剪贴板获取
          source = 'clipboard';
          const clipboardImage = await this.getImageFromClipboard();
    
          if (!clipboardImage) {
            throw new Error('无法获取图片:没有提供文件路径且剪贴板中没有图片');
          }
    
          finalImagePath = clipboardImage;
          logger.info('从剪贴板获取图片', { path: finalImagePath });
        }
    
        // 分析图片
        const result = await this.analyzeImageFile(finalImagePath, focusArea);
    
        // 如果是剪贴板或URL下载的图片,清理临时文件
        if (source === 'clipboard' || source === 'url') {
          await this.cleanupTempFile(finalImagePath);
        }
    
        return {
          ...result,
          source,
        };
      } catch (error) {
        logger.error('自动获取并分析图片失败', { error });
        throw new Error(`自动处理图片失败: ${error instanceof Error ? error.message : '未知错误'}`);
      }
    }
  • src/index.ts:40-65 (registration)
    Registration of the tool in the ListToolsRequestSchema handler, including name, description, and input schema.
    this.server.setRequestHandler(ListToolsRequestSchema, async () => {
      return {
        tools: [
          {
            name: 'auto_analyze_image',
            description: '自动获取并分析图片(支持文件路径、网络URL或剪贴板)',
            inputSchema: {
              type: 'object',
              properties: {
                imagePath: {
                  type: 'string',
                  description: '图片文件路径或网络URL(可选,不提供则使用剪贴板)',
                },
                focusArea: {
                  type: 'string',
                  enum: ['code', 'architecture', 'error', 'documentation'],
                  description: '分析重点区域',
                  default: 'code',
                },
              },
              required: [],
            },
          },
        ],
      };
    });
  • src/index.ts:76-81 (registration)
    Dispatch logic in CallToolRequestSchema handler that invokes the auto_analyze_image handler when the tool name matches.
    if (name === 'auto_analyze_image') {
      result = await this.autoImageService.autoGetAndAnalyzeImage(
        typedArgs.imagePath,
        typedArgs.focusArea || 'code'
      );
    } else {
  • TypeScript interface defining the structure of the image analysis result returned by the tool.
    export interface ImageAnalysisResult {
      description?: string;
      content?: string;
      type?: string;
      layout?: string;
      issues?: string[];
      details?: string;
      summary: string;
      confidence: number;
      metadata?: {
        format?: string;
        width?: number;
        height?: number;
        fileSize?: string;
      };
    }
  • Helper method that processes the image file (resize, jpeg, base64), extracts metadata, calls GLMService for analysis, and structures the result.
    private async analyzeImageFile(
      imagePath: string,
      focusArea: 'code' | 'architecture' | 'error' | 'documentation' = 'code'
    ): Promise<ImageAnalysisResult> {
      try {
        // 读取图片文件
        const imageBuffer = await fs.readFile(imagePath);
        
        // 使用 sharp 处理图片
        const sharp = require('sharp');
        const processedImage = await sharp(imageBuffer)
          .jpeg({ quality: 90 })
          .resize(2048, 2048, { fit: 'inside', withoutEnlargement: true })
          .toBuffer();
    
        const base64 = processedImage.toString('base64');
    
        // 获取基本信息
        const metadata = await sharp(imageBuffer).metadata();
        const fileSize = (imageBuffer.length / 1024).toFixed(2) + ' KB';
    
        // 使用 GLM 服务分析图片
        const analysisResult = await this.glmService.analyzeCode(base64, focusArea);
    
        // 解析结果
        let result: ImageAnalysisResult;
        
        try {
          // 尝试解析JSON响应
          const parsed = JSON.parse(analysisResult);
          result = {
            description: parsed.description || parsed.content,
            type: parsed.type,
            layout: parsed.layout,
            issues: parsed.issues,
            details: parsed.details,
            summary: parsed.summary || analysisResult.substring(0, 500),
            confidence: 0.9,
            metadata: {
              format: metadata.format,
              width: metadata.width,
              height: metadata.height,
              fileSize,
            },
          };
        } catch {
          // 如果不是JSON格式,直接使用文本响应
          result = {
            summary: analysisResult,
            confidence: 0.8,
            metadata: {
              format: metadata.format,
              width: metadata.width,
              height: metadata.height,
              fileSize,
            },
          };
        }
    
        return result;
      } catch (error) {
        logger.error('分析图片文件失败', { path: imagePath, error });
        throw new Error(`分析图片失败: ${error instanceof Error ? error.message : '未知错误'}`);
      }
    }
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 mentions '自动获取并分析' (automatically acquire and analyze), which implies some automation and processing, but does not describe what '分析' (analyze) entails (e.g., what kind of analysis is performed, output format, potential rate limits, or authentication needs). 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.

Conciseness4/5

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

The description is a single, efficient sentence that front-loads the core purpose ('自动获取并分析图片') and includes essential details (input sources) without unnecessary elaboration. It is appropriately sized for the tool's complexity, though it could be slightly more structured (e.g., by separating purpose from usage hints).

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 (image analysis tool with automation), no annotations, and no output schema, the description is incomplete. It does not explain what the analysis returns, how results are formatted, or any behavioral traits like error handling or performance characteristics. This makes it inadequate for an agent to fully understand the tool's context and usage.

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 both parameters thoroughly. The description adds marginal value by mentioning the three input sources (file path, network URL, clipboard) for the 'imagePath' parameter, but this is largely redundant with the schema's description. It does not provide additional meaning beyond the schema, so the baseline score of 3 is appropriate.

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: '自动获取并分析图片' (automatically acquire and analyze images). It specifies the verb '获取并分析' (acquire and analyze) and the resource '图片' (images), and mentions three input sources (file path, network URL, or clipboard). However, without sibling tools, we cannot assess differentiation, so it cannot receive a 5.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage by listing supported input sources (file path, network URL, clipboard), suggesting when to use it based on available image data. However, it lacks explicit guidance on when to use this tool versus alternatives (e.g., other image analysis tools), prerequisites, or exclusions. With no sibling tools, this is adequate but not comprehensive.

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/lengbone/mcp-vl'

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