optimize_image
Optimize images by resizing and adjusting quality to reduce file size while maintaining aspect ratio. Specify input and output paths, target dimensions, and compression settings for efficient image management.
Instructions
Create an optimized version of an image
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| height | No | Target height (maintains aspect ratio if only height is specified) | |
| inputPath | Yes | Path to the input image | |
| outputPath | Yes | Path where to save the optimized image | |
| quality | No | JPEG/WebP quality (1-100) | |
| width | No | Target width (maintains aspect ratio if only width is specified) |
Input Schema (JSON Schema)
{
"properties": {
"height": {
"description": "Target height (maintains aspect ratio if only height is specified)",
"type": "number"
},
"inputPath": {
"description": "Path to the input image",
"type": "string"
},
"outputPath": {
"description": "Path where to save the optimized image",
"type": "string"
},
"quality": {
"description": "JPEG/WebP quality (1-100)",
"maximum": 100,
"minimum": 1,
"type": "number"
},
"width": {
"description": "Target width (maintains aspect ratio if only width is specified)",
"type": "number"
}
},
"required": [
"inputPath",
"outputPath"
],
"type": "object"
}
Implementation Reference
- src/index.ts:193-238 (handler)The core handler function for the optimize_image tool that uses the Sharp library to read the input image, optionally resize it while maintaining aspect ratio, apply quality settings for JPEG/WebP, and save the optimized image to the output path. Handles errors gracefully.private async handleOptimizeImage(args: OptimizeImageArgs) { try { // Ensure output directory exists await fs.ensureDir(path.dirname(args.outputPath)); // Read input image let transformer = sharp(args.inputPath); // Resize if dimensions specified if (args.width || args.height) { transformer = transformer.resize(args.width, args.height, { fit: 'inside', withoutEnlargement: true, }); } // Set quality if specified if (args.quality) { transformer = transformer.jpeg({ quality: args.quality }).webp({ quality: args.quality }); } // Save optimized image await transformer.toFile(args.outputPath); return { content: [ { type: 'text', text: `Successfully optimized image to ${args.outputPath}`, }, ], }; } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred'; console.error('Optimization error:', errorMessage); return { content: [ { type: 'text', text: `Failed to optimize image: ${errorMessage}`, }, ], isError: true, }; } }
- src/index.ts:95-126 (registration)Registration of the optimize_image tool in the ListTools response, providing the tool name, description, and detailed JSON input schema for MCP clients.{ name: 'optimize_image', description: 'Create an optimized version of an image', inputSchema: { type: 'object', properties: { inputPath: { type: 'string', description: 'Path to the input image', }, outputPath: { type: 'string', description: 'Path where to save the optimized image', }, width: { type: 'number', description: 'Target width (maintains aspect ratio if only width is specified)', }, height: { type: 'number', description: 'Target height (maintains aspect ratio if only height is specified)', }, quality: { type: 'number', description: 'JPEG/WebP quality (1-100)', minimum: 1, maximum: 100, }, }, required: ['inputPath', 'outputPath'], }, },
- src/index.ts:20-26 (schema)TypeScript interface defining the shape of arguments for the optimize_image tool, used for type safety in the handler and validator.interface OptimizeImageArgs { inputPath: string; outputPath: string; width?: number; height?: number; quality?: number; }
- src/index.ts:62-72 (helper)Type guard helper function that validates whether provided arguments conform to OptimizeImageArgs interface before dispatching to the handler.private isOptimizeImageArgs(args: unknown): args is OptimizeImageArgs { if (!args || typeof args !== 'object') return false; const a = args as Record<string, unknown>; return ( typeof a.inputPath === 'string' && typeof a.outputPath === 'string' && (a.width === undefined || typeof a.width === 'number') && (a.height === undefined || typeof a.height === 'number') && (a.quality === undefined || typeof a.quality === 'number') ); }
- src/index.ts:137-141 (registration)Dispatch logic in the CallToolRequest handler that routes optimize_image calls, performs argument validation, and invokes the main handler.case 'optimize_image': if (!this.isOptimizeImageArgs(request.params.arguments)) { throw new McpError(ErrorCode.InvalidParams, 'Invalid arguments for optimize_image'); } return this.handleOptimizeImage(request.params.arguments);