Skip to main content
Glama
qpd-v

mcp-image-downloader

by qpd-v

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

TableJSON Schema
NameRequiredDescriptionDefault
heightNoTarget height (maintains aspect ratio if only height is specified)
inputPathYesPath to the input image
outputPathYesPath where to save the optimized image
qualityNoJPEG/WebP quality (1-100)
widthNoTarget width (maintains aspect ratio if only width is specified)

Implementation Reference

  • 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'],
      },
    },
  • 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;
    }
  • 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);
Behavior2/5

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

With no annotations provided, the description carries full burden but only states the basic action without disclosing behavioral traits like performance characteristics, error conditions, or side effects. It mentions optimization but doesn't explain what that entails (e.g., compression, format changes).

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 with zero wasted words. It's front-loaded with the core purpose and appropriately sized for the tool's complexity.

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?

For a mutation tool with no annotations and no output schema, the description is insufficient. It doesn't explain what 'optimized' means, what formats are supported, or what happens on failure. The context signals indicate moderate complexity (5 parameters) that warrants more explanation.

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 thoroughly. The description adds no additional parameter semantics beyond what's in the schema, meeting the baseline for high coverage.

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 action ('Create an optimized version') and resource ('of an image'), making the purpose immediately understandable. It distinguishes from the sibling 'download_image' by focusing on transformation rather than retrieval, though it doesn't explicitly contrast them.

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, nor does it mention prerequisites or constraints. It simply states what the tool does without context about appropriate scenarios or limitations.

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/qpd-v/mcp-image-downloader'

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