Skip to main content
Glama
InhiblabCore

mcp-image-compression

by InhiblabCore

image_compression

Compress images by providing image URLs to reduce file size. Optionally set output format and number of results.

Instructions

Compress an image

Input Schema

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

Implementation Reference

  • The handleToolCall method that dispatches to 'image_compression' case, parsing URLs, calling compressAndStoreImage, and returning results.
    private async handleToolCall(name: string, args: any): Promise<CallToolResult> {
      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}`
            );
          }
        }
        default: {
          throw new McpError(ErrorCode.MethodNotFound, `Tool ${name} not found`, {
            code: ErrorCode.MethodNotFound,
            message: `Tool ${name} not found`
          });
        }
    
      }
    }
  • The tool definition (TOOLS array) with inputSchema for 'image_compression', specifying required 'urls' field and optional 'format' and default quality=80.
    const TOOLS: Tool[] = [
      {
        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-81 (registration)
    The setupHandlers method that registers the tool list (ListToolsRequestSchema) and tool call handler (CallToolRequestSchema) on the MCP server, linking the TOOLS array to the handler.
    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 ?? {})
      );
  • The compressAndStoreImage helper function that downloads/reads an image, compresses it with sharp (using configurable quality and format), saves it to the output directory, and returns the output 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`);
      }
    }
  • The isImageSource helper function that validates whether a string is a valid image source (file extension, base64 data URI, or CDN-style URL with format parameter).
    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;
    }
Behavior1/5

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

With no annotations, the description carries full burden to disclose behavioral traits. It says nothing about whether the compression modifies the original, what is returned, rate limits, or supported size limits. The agent has no clue about side effects or constraints.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness3/5

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

The description is extremely short (one phrase), which makes it concise, but it is under-specified. It achieves conciseness at the expense of critical information, so it does not earn its place fully. A balanced description would be more effective.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness1/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of image compression and the lack of an output schema or annotations, the description is grossly incomplete. It omits information about output format, error handling, supported input types, and the meaning of the 'quantity' parameter. An agent cannot reliably use this tool without further clarification.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100% but the description adds no meaning beyond the schema. Moreover, the 'quantity' parameter's description ('Number of transcripts to return') is confusingly unrelated to image compression, and the description does nothing to clarify this mismatch. Baseline 3 is reduced because the description fails to add value or resolve ambiguity.

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 states the verb 'Compress' and the resource 'an image', which is clear and specific. It is not a tautology and distinguishes the tool's core action. However, it lacks details on supported formats or output behavior, so not 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 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, prerequisites, or alternatives. The description simply states what it does without any context for appropriate usage scenarios.

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

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