Skip to main content
Glama
ccw33
by ccw33

vision_query

Analyze images to extract text via OCR, answer visual questions, detect objects, or generate descriptions using the GLM-4.5V model.

Instructions

调用 GLM-4.5V 对图片进行 OCR/问答/检测

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYes图片路径或URL
promptYes查询提示词
modeNo查询模式describe
returnJsonNo是否返回JSON格式结果

Implementation Reference

  • Core handler function implementing the vision_query tool logic: loads and compresses image, builds GLM-4V API payload, makes API call, normalizes response.
    async function visionQuery(imagePath: string, prompt: string, mode: string, returnJson: boolean): Promise<VisionResult> {
      try {
        let imageBase64: string;
    
        let buffer: Buffer;
        
        if (imagePath.startsWith("data:")) {
          // Data URL 格式
          const base64Data = imagePath.split(',')[1];
          if (!base64Data) {
            throw new Error("Invalid data URL format");
          }
          buffer = Buffer.from(base64Data, 'base64');
        } else if (imagePath.startsWith("http://") || imagePath.startsWith("https://")) {
          // HTTP/HTTPS URL图片
          const response = await fetch(imagePath);
          if (!response.ok) {
            throw new Error(`Failed to fetch image: ${response.statusText}`);
          }
          buffer = Buffer.from(await response.arrayBuffer());
        } else {
          // 本地文件
          const resolvedPath = path.resolve(imagePath);
          buffer = await fs.readFile(resolvedPath);
        }
        
        // 压缩图片以减少token使用量
        const compressedBuffer = await compressImage(buffer, 800, 75); // 更小尺寸和质量
        imageBase64 = compressedBuffer.toString("base64");
    
        const payload = buildGlmPayload({
          prompt,
          imageBase64,
          mode,
          returnJson
        });
    
        const glmBaseUrl = process.env.GLM_BASE_URL || "https://open.bigmodel.cn/api/paas/v4/chat/completions";
        const glmApiKey = process.env.GLM_API_KEY;
    
        if (!glmApiKey) {
          throw new Error("GLM_API_KEY environment variable is required");
        }
    
        const response = await fetch(glmBaseUrl, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "Authorization": `Bearer ${glmApiKey}`
          },
          body: JSON.stringify(payload)
        });
    
        if (!response.ok) {
          throw new Error(`GLM API request failed: ${response.statusText}`);
        }
    
        const data = await response.json();
        const result = normalizeGlmResult(data, { mode, returnJson });
    
        return {
          ok: true,
          result,
          metadata: {
            mode,
            returnJson,
            timestamp: Date.now()
          }
        };
      } catch (error) {
        return {
          ok: false,
          error: error instanceof Error ? error.message : "Unknown error"
        };
      }
    }
  • src/index.ts:81-110 (registration)
    MCP tool registration for 'vision_query', including description, Zod input schema, and thin wrapper handler calling the core visionQuery function.
    mcpServer.registerTool("vision_query", {
      description: "调用 GLM-4.5V 对图片进行 OCR/问答/检测",
      inputSchema: {
        path: z.string().describe("图片路径或URL"),
        prompt: z.string().describe("查询提示词"),
        mode: z.enum(["describe", "ocr", "qa", "detect"]).default("describe").describe("查询模式"),
        returnJson: z.boolean().default(false).describe("是否返回JSON格式结果"),
      },
    }, async ({ path: imagePath, prompt, mode, returnJson }) => {
      try {
        const result = await visionQuery(imagePath, prompt, mode, returnJson);
        return {
          content: [{
            type: "text" as const,
            text: JSON.stringify(result, null, 2)
          }]
        };
      } catch (error) {
        return {
          content: [{
            type: "text" as const,
            text: JSON.stringify({
              ok: false,
              error: error instanceof Error ? error.message : "Unknown error"
            }, null, 2)
          }],
          isError: true
        };
      }
    });
  • TypeScript interface defining the output structure for visionQuery results.
    interface VisionResult {
      ok: boolean;
      result?: string | object;
      error?: string;
      metadata?: {
        mode: string;
        returnJson: boolean;
        timestamp: number;
      };
    }
  • Helper function to build the payload for GLM vision API call, customizing system prompt based on mode.
    function buildGlmPayload(opts: {
      prompt: string;
      imageBase64: string;
      mode: string;
      returnJson: boolean;
    }) {
      const { prompt, imageBase64, mode, returnJson } = opts;
      
      // 截断过长的 prompt
      const truncatedPrompt = truncatePrompt(prompt, 300);
      
      let systemPrompt = "";
      switch (mode) {
        case "ocr":
          systemPrompt = "识别图片中的文字。";
          break;
        case "qa":
          systemPrompt = "根据图片回答问题。";
          break;
        case "detect":
          systemPrompt = "识别图片中的物体。";
          break;
        default:
          systemPrompt = "描述图片内容。";
      }
    
      if (returnJson) {
        systemPrompt += "用JSON格式回答。";
      }
    
      return {
        model: "glm-4v-plus",
        messages: [
          {
            role: "system",
            content: systemPrompt
          },
          {
            role: "user",
            content: [
              {
                type: "text",
                text: truncatedPrompt
              },
              {
                type: "image_url",
                image_url: {
                  url: `data:image/jpeg;base64,${imageBase64}`
                }
              }
            ]
          }
        ],
        temperature: 0.1,
        max_tokens: 1000
      };
    }
  • Helper function to normalize GLM API response, parsing JSON if requested.
    function normalizeGlmResult(data: any, opts: { mode: string; returnJson: boolean }) {
      if (data.error) {
        throw new Error(data.error.message || "GLM API error");
      }
    
      const content = data.choices?.[0]?.message?.content || "";
      
      if (opts.returnJson) {
        try {
          return JSON.parse(content);
        } catch {
          return { text: content, parsed: false };
        }
      }
    
      return content;
    }
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 mentions the AI model ('GLM-4.5V') and general capabilities but lacks critical details: it doesn't specify output format (though 'returnJson' parameter hints at this), rate limits, authentication needs, error handling, or performance characteristics. The description is too vague for a tool with AI inference capabilities.

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 in Chinese that directly states the tool's purpose. It's front-loaded with the core action and avoids unnecessary words. However, it could be slightly more structured by separating the three capabilities for clarity, but it remains appropriately concise.

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 an AI vision tool with no annotations and no output schema, the description is incomplete. It doesn't explain what the tool returns (e.g., text, structured data), how to interpret results, or any limitations (e.g., image size, format support). For a 4-parameter tool invoking an AI model, this leaves significant gaps for an agent to use it effectively.

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 four parameters. The description adds no parameter-specific information beyond what's in the schema—it doesn't explain the 'mode' enum values or how 'prompt' interacts with different modes. Baseline 3 is appropriate since the schema does the heavy lifting, but the description doesn't compensate with additional context.

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 action ('调用 GLM-4.5V 对图片进行') and the resource ('图片'), specifying three capabilities: OCR, Q&A, and detection. It distinguishes from sibling tools like 'process_file' and 'read_image' by focusing on AI-powered analysis rather than basic file operations. However, it doesn't explicitly differentiate between the three modes or mention the default 'describe' mode from the schema.

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 like 'process_file' or 'read_image'. It lists capabilities but doesn't specify scenarios, prerequisites, or exclusions. For example, it doesn't indicate whether it's for complex AI analysis versus simple image reading, leaving usage context entirely implicit.

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/ccw33/Multimodel-MCP'

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