Skip to main content
Glama
ccw33
by ccw33

read_image

Extract dataURL and dimensions from local or URL-based images for processing in multimodal AI workflows.

Instructions

读取本地/URL图片并返回 dataURL 与尺寸信息

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYes图片路径或URL
maxSideNo最大边长,用于缩放

Implementation Reference

  • Core handler function for reading images from local paths, URLs, or data URLs, compressing them using sharp, and returning a data URL with dimensions in ImageResult format.
    async function readImage(imagePath: string, maxSide?: number): Promise<ImageResult> {
      try {
        console.error(`[DEBUG] readImage called with path: ${imagePath.substring(0, 50)}...`);
        console.error(`[DEBUG] Path starts with data:? ${imagePath.startsWith("data:")}`);
        
        let buffer: Buffer;
    
        if (imagePath.startsWith("data:")) {
          // Data URL 格式
          console.error(`[DEBUG] Processing data URL in readImage`);
          const commaIndex = imagePath.indexOf(',');
          if (commaIndex === -1) {
            throw new Error("Invalid data URL format: no comma found");
          }
          const base64Data = imagePath.substring(commaIndex + 1);
          if (!base64Data) {
            throw new Error("Invalid data URL format: no base64 data");
          }
          console.error(`[DEBUG] Base64 data length: ${base64Data.length}`);
          buffer = Buffer.from(base64Data, 'base64');
        } else if (imagePath.startsWith("http://") || imagePath.startsWith("https://")) {
          // HTTP/HTTPS URL图片
          console.error(`[DEBUG] Fetching HTTP/HTTPS image`);
          const response = await fetch(imagePath);
          if (!response.ok) {
            throw new Error(`Failed to fetch image: ${response.statusText}`);
          }
          buffer = Buffer.from(await response.arrayBuffer());
        } else {
          // 本地文件
          console.error(`[DEBUG] Reading local file: ${imagePath}`);
          const resolvedPath = path.resolve(imagePath);
          buffer = await fs.readFile(resolvedPath);
        }
    
        console.error(`[DEBUG] Original buffer size: ${buffer.length}`);
        // 压缩图片
        const compressedBuffer = await compressImage(buffer, maxSide || 1024);
        console.error(`[DEBUG] Compressed buffer size: ${compressedBuffer.length}`);
        
        const mime = "image/jpeg"; // 压缩后统一为 JPEG 格式
        const dataUrl = `data:${mime};base64,${compressedBuffer.toString("base64")}`;
    
        return {
          ok: true,
          image: {
            source: imagePath,
            mime,
            dataUrl,
            width: (await sharp(compressedBuffer).metadata()).width,
            height: (await sharp(compressedBuffer).metadata()).height
          }
        };
      } catch (error) {
        return {
          ok: false,
          error: error instanceof Error ? error.message : "Unknown error"
        };
      }
    }
  • src/index.ts:51-78 (registration)
    Registers the 'read_image' tool with the MCP server, defining input schema and a wrapper handler that calls the core readImage function and formats the response.
    mcpServer.registerTool("read_image", {
      description: "读取本地/URL图片并返回 dataURL 与尺寸信息",
      inputSchema: {
        path: z.string().describe("图片路径或URL"),
        maxSide: z.number().optional().describe("最大边长,用于缩放"),
      },
    }, async ({ path: imagePath, maxSide }) => {
      try {
        const result = await readImage(imagePath, maxSide);
        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 of the read_image tool, including success flag, image details (dataUrl, dimensions), or error.
    interface ImageResult {
      ok: boolean;
      image?: {
        source: string;
        mime: string;
        dataUrl: string;
        width?: number;
        height?: number;
      };
      error?: string;
    }
  • Helper function to compress image buffers using Sharp library, resizing to maxSide while maintaining aspect ratio and converting to JPEG.
    async function compressImage(buffer: Buffer, maxSide: number = 1024, quality: number = 80): Promise<Buffer> {
      try {
        const image = sharp(buffer);
        const metadata = await image.metadata();
        
        let width = metadata.width || 1024;
        let height = metadata.height || 1024;
        
        // 计算缩放比例
        if (width > maxSide || height > maxSide) {
          const ratio = Math.min(maxSide / width, maxSide / height);
          width = Math.round(width * ratio);
          height = Math.round(height * ratio);
        }
        
        return await image
          .resize(width, height, { fit: 'inside' })
          .jpeg({ quality, progressive: true })
          .toBuffer();
      } catch (error) {
        console.error("Image compression failed:", error);
        return buffer; // 失败时返回原始buffer
      }
    }
Behavior2/5

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

No annotations are provided, so the description carries full burden. It states the tool reads images and returns dataURL with dimensions, but lacks details on error handling (e.g., invalid paths, unsupported formats), performance (e.g., size limits, rate limits), or side effects (e.g., caching). This is a significant gap for a tool with no annotation coverage.

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 sentence in Chinese that front-loads the core functionality ('读取本地/URL图片') and specifies the return value ('返回 dataURL 与尺寸信息'). There is zero waste, making it appropriately sized and well-structured.

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 no annotations and no output schema, the description is incomplete. It doesn't explain the return format (e.g., structure of dataURL and dimensions), error cases, or prerequisites (e.g., network access for URLs). For a tool with 2 parameters and no structured output, more context is needed to be fully helpful.

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 ('path' and 'maxSide'). The description adds no additional meaning beyond what the schema provides, such as examples or constraints. Baseline 3 is appropriate when 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 verb ('读取' meaning 'read') and resource ('图片' meaning 'image'), specifying it reads local or URL images and returns dataURL with dimension information. It distinguishes from sibling 'process_file' and 'vision_query' by focusing on basic image reading rather than processing or querying, though the distinction could be more explicit.

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 'vision_query'. It mentions local/URL sources but doesn't specify scenarios where this tool is preferred over siblings, leaving usage context implied rather than explicit.

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