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
| Name | Required | Description | Default |
|---|---|---|---|
| format | No | Image format | |
| quantity | No | Number of transcripts to return | |
| urls | Yes | URL of the image to compress,If it's a local file, do not add any prefix. array join by ',' |
Input Schema (JSON Schema)
{
"properties": {
"format": {
"description": "Image format",
"type": "string"
},
"quantity": {
"default": 80,
"description": "Number of transcripts to return",
"type": "number"
},
"urls": {
"description": "URL of the image to compress,If it's a local file, do not add any prefix. array join by ','",
"type": "string"
}
},
"required": [
"urls"
],
"type": "object"
}
Implementation Reference
- src/index.ts:87-130 (handler)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}` ); } }
- src/index.ts:15-37 (schema)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 ?? {}) ); }
- src/common.ts:14-63 (helper)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`); } }
- src/common.ts:65-83 (helper)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; }