Skip to main content
Glama
InhiblabCore

mcp-image-compression

by InhiblabCore

image_compression

Reduce image file sizes by compressing images in various formats using URLs or local files. Supports customized compression levels and output formats for optimized storage and faster loading.

Instructions

Compress an image

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
formatNoImage format
quantityNoNumber of transcripts to return
urlsYesURL of the image to compress,If it's a local file, do not add any prefix. array join by ','

Implementation Reference

  • Main handler logic for the image_compression tool within handleToolCall: parses arguments, validates image sources, sets download directory, loops over images to compress and store using helper, returns success message with output paths or errors.
    const { urls, quality = 80, format = null } = args;
    
    const imageSources = (urls as string)?.split(",")?.filter((url) => isImageSource(url));
    if (this.downloadDir === '') {
      throw new McpError(
        ErrorCode.InvalidParams,
        `downloadDir is empty, please set the environment variable IMAGE_COMPRESSION_DOWNLOAD_DIR`
      );
    }
    
    let outputPaths = []
    switch (name) {
      case "image_compression": {
        try {
          const isMutipleUrls = imageSources.length > 1;
          const downloadDir = isMutipleUrls ? path.join(this.downloadDir, 'thumbs') : this.downloadDir;
          // 循环处理每个 URL
          // 压缩并存储图片
          for (const key in imageSources) {
            const imageUrl = imageSources[key];
            const outputPath = await compressAndStoreImage(imageUrl, downloadDir, quality, format)
            outputPaths.push(outputPath)
          }
          return {
            content: [{
              type: "text",
              text: `success image compression ${outputPaths}`,
            }],
            metadata: {
              timestamp: new Date().toISOString(),
            },
            isError: false
          }
        } catch (error) {
          if (error instanceof McpError) {
            throw error;
          }
    
          throw new McpError(
            ErrorCode.InternalError,
            `Failed to process transcript: ${(error as Error).message}`
          );
        }
      }
  • Tool schema definition for 'image_compression' including input parameters: urls (required, comma-separated), quantity (default 80), format.
    {
      name: "image_compression",
      description: "Compress an image",
      inputSchema: {
        type: "object",
        properties: {
          urls: {
            type: "string",
            description: "URL of the image to compress,If it's a local file, do not add any prefix. array join by ','",
          },
          quantity: {
            type: "number",
            description: "Number of transcripts to return",
            default: 80
          },
          format: {
            type: "string",
            description: "Image format",
          }
        },
        required: ["urls"]
      }
    }
  • src/index.ts:72-82 (registration)
    Registers MCP handlers for listing tools (returns TOOLS array with image_compression) and calling tools (delegates to handleToolCall).
    private setupHandlers() {
      // List available tools
      this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
        tools: TOOLS
      }));
    
      // Handle tool calls
      this.server.setRequestHandler(CallToolRequestSchema, async (request) =>
        this.handleToolCall(request.params.name, request.params.arguments ?? {})
      );
    }
  • Core helper function that downloads image from URL or reads local file, compresses/converts using Sharp library to specified quality/format, generates unique filename, stores in output directory, returns the output file path.
    export async function compressAndStoreImage(
      imageUrl: ImageSource,
      outputDir: string,
      quality = 80,
      format = 'jpg',
    ): Promise<string> {
      try {
        // 校验输出目录
        if (!fs.existsSync(outputDir)) {
          fs.mkdirSync(outputDir, { recursive: true });
        }
    
        let inputBuffer: Buffer;
    
        // 判断是否是网络地址
        if (/^https?:\/\//.test(imageUrl)) {
          // 下载网络图片
          const response = await axios.get(imageUrl, {
            responseType: 'arraybuffer',
            timeout: 10000
          });
          inputBuffer = Buffer.from(response.data, 'binary');
        } else {
          // 读取本地图片
          if (!fs.existsSync(imageUrl)) {
            throw new Error(`Local file not found: ${imageUrl}`);
          }
          inputBuffer = await fs.promises.readFile(imageUrl);
        }
    
        // 读取文件原始名称
        const originalFilename = path.basename(imageUrl);
        const originalExt = path.parse(originalFilename).ext;
    
        // 生成唯一文件名
        const outputFilename = format ? `${uuidv4()}.${format}` : `${uuidv4()}${originalExt}`;
        const outputPath = path.join(outputDir, outputFilename);
    
        await sharp(inputBuffer)
          // @ts-ignore
          .toFormat(format ? format : originalExt?.replace('.', ''), {
            quality,
          })
          .toFile(outputPath);
    
        return outputPath;
      } catch (error) {
        throw new Error(`Image processing failed`);
      }
    }
  • Utility function to check if a string represents a valid image source (file extension, base64 data URI, or image CDN paths). Used to filter input URLs.
    export function isImageSource(str: string): boolean {
      // 匹配常规图片地址
      if (/\.(jpe?g|png|gif|webp|bmp|svg|avif)(\?[^#]*)?(#[^\s]*)?$/i.test(str)) {
        return true;
      }
    
      // 匹配Base64数据URI
      if (/^data:image\/(jpe?g|png|gif|webp|bmp|svg\+xml|avif);base64,/i.test(str)) {
        return true;
      }
    
      // 可选:匹配无扩展名但包含图片路由的情况(如CDN地址)
      // 示例:/image/12345?format=jpg
      if (/\/(image|img|photo|pic)s?\/[^/]+(\?.*?(format|type)=(jpe?g|png|gif|webp|bmp|svg|avif))/i.test(str)) {
        return true;
      }
    
      return false;
    }
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. 'Compress an image' implies a mutation operation, but it doesn't specify side effects (e.g., quality loss, format changes), permissions needed, rate limits, or error handling. This leaves significant gaps for a tool that likely alters data.

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 ('Compress an image') with no wasted words, making it front-loaded and easy to parse. It efficiently conveys the core purpose in minimal space, though this brevity contributes to gaps in other dimensions.

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 image compression tool with no annotations and no output schema, the description is incomplete. It doesn't explain what compression entails, the expected output, error conditions, or how parameters interact. For a mutation tool with undocumented behavior, this is inadequate.

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 all parameters (format, quantity, urls). The description adds no additional meaning beyond the schema, such as explaining how 'quantity' relates to 'transcripts' (which seems mismatched) or clarifying the 'urls' format. 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.

Purpose3/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description 'Compress an image' states the basic action (compress) and resource (image), which provides a minimal viable purpose. However, it's vague about scope (single vs. multiple images) and doesn't distinguish from siblings (though none exist). It doesn't specify what compression entails (e.g., size reduction, quality loss).

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?

No guidance is provided on when to use this tool versus alternatives. The description lacks context about prerequisites (e.g., image formats supported), exclusions, or typical use cases. With no sibling tools, differentiation isn't needed, but basic usage context is missing.

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

Related 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/InhiblabCore/mcp-image-compression'

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