Skip to main content
Glama
srigi

Google Images Search MCP

by srigi

persist_image

Download an image from a URL and save it to a specified folder in your workspace. The folder is created automatically if it does not exist.

Instructions

Store image at URL to folder relative to current workspace. If targetPath does not exist, the tool will create it automatically.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
urlYesURL of the image
targetPathYesFolder where to save the image (relative to the current workspace)
workspacePathYesThe current workspace absolute path

Implementation Reference

  • src/index.ts:20-26 (registration)
    Registration of the 'persist_image' tool with the MCP server, binding schema and handler.
    server.tool('search_image', 'Search the image(s) online', searchImageSchema, searchImageHandler);
    server.tool(
      'persist_image',
      'Store image at URL to folder relative to current workspace. If targetPath does not exist, the tool will create it automatically.',
      persistImageSchema,
      persistImageHandler,
    );
  • Schema definition for persist_image: url (string URL), targetPath (string folder), workspacePath (string absolute path).
    export const schema = {
      url: z.string().url().describe('URL of the image'),
      targetPath: z.string().describe('Folder where to save the image (relative to the current workspace)'),
      workspacePath: z.string().describe('The current workspace absolute path'),
    } as const;
  • Main handler function that prepares target path, fetches the image, and returns success/error response.
    export const handler: ToolCallback<typeof schema> = async ({ url, targetPath, workspacePath }) => {
      logger().info('handler called', { url, targetPath, workspacePath });
    
      const [prepareTargetPathErr, fullTargetPath] = await tryCatch<PersistImageError, string>(prepareTargetPath(workspacePath, targetPath));
      if (prepareTargetPathErr != null) {
        logger().error('prepareTargetPath error', { error: prepareTargetPathErr });
    
        return {
          _meta: {
            error: {
              type: 'PersistImageError',
              message: prepareTargetPathErr.message,
              code: prepareTargetPathErr.code,
            },
          },
          content: [
            {
              type: 'text' as const,
              text: `Error: ${prepareTargetPathErr.message}`,
            },
          ],
        };
      }
    
      const [fetchImageErr, fetchResult] = await tryCatch<PersistImageError, FetchResult>(fetchImage(url, fullTargetPath));
      if (fetchImageErr != null) {
        logger().error('fetchImage error', { error: fetchImageErr });
    
        return {
          _meta: {
            error: {
              type: 'PersistImageError',
              message: fetchImageErr.message,
              code: fetchImageErr.code,
            },
          },
          content: [
            {
              type: 'text' as const,
              text: `Error: ${fetchImageErr.message}`,
            },
          ],
        };
      }
    
      const _meta = {
        success: true,
        filePersistPath: fetchResult.filePersistPath,
        size: fetchResult.size,
        mimeType: fetchResult.mimeType,
      };
      logger().info('handler success', { fetchResult, _meta });
    
      return {
        _meta,
        content: [
          {
            type: 'text' as const,
            text: `All done! Download result:\n- filePersistPath: ${relative(workspacePath, fetchResult.filePersistPath)}\n- size: ${Math.round((fetchResult.size / 1024) * 100) / 100}KB`,
          },
        ],
      };
    };
  • prepareTargetPath validates target is within project directory and creates it if needed.
    export async function prepareTargetPath(workspacePath: string, targetPath: string): Promise<string> {
      logger().info('prepareTargetPath()', { workspacePath, targetPath });
    
      // validates that the target path is within project bounds, and returns the full path of the directory where the file should be saved
      if (targetPath.startsWith('..')) {
        throw new PersistImageError('Target path must be within the project directory', 'INVALID_PATH');
      }
    
      const fullTargetPath = resolve(workspacePath, targetPath);
      const [fsAccessErr] = await tryCatch(fs.access(fullTargetPath));
      logger().debug('prepareTargetPath() resolve & fs.access', { fullTargetPath, fsAccessErr });
    
      if (fsAccessErr == null) {
        logger().info('prepareTargetPath() existing directory found');
        return fullTargetPath;
      }
    
      const [fsMkdirErr] = await tryCatch(fs.mkdir(fullTargetPath, { recursive: true }));
      logger().debug('prepareTargetPath() fs.mkdir', { fsMkdirErr });
    
      if (fsMkdirErr == null) {
        logger().info('prepareTargetPath() directory created successfully');
        return fullTargetPath;
      }
    
      throw new PersistImageError(`Failed to create directory: ${fsAccessErr.message}`, 'DIRECTORY_CREATE_FAILED');
    }
  • fetchImage downloads image from URL, validates content type is an allowed image type, determines filename, and writes to disk.
    export async function fetchImage(url: string, fullTargetPath: string): Promise<FetchResult> {
      logger().info('fetchImage()', { url, fullTargetPath });
    
      const [fetchErr, response] = await tryCatch(fetch(url, { headers: { 'User-Agent': USER_AGENT } }));
      logger().info('fetchImage() response', { fetchErr, response });
    
      if (fetchErr != null) {
        throw new PersistImageError(`Failed to fetch image: ${fetchErr.message}`, 'FETCH_FAILED');
      }
      if (!response.ok) {
        throw new PersistImageError(`HTTP error ${response.status}: ${response.statusText}`, 'HTTP_ERROR');
      }
      if (response.body == null) {
        throw new PersistImageError('No response body received', 'NO_RESPONSE_BODY');
      }
    
      const contentType = response.headers.get('content-type') || '';
      if (!ALLOWED_IMAGE_TYPES.has(contentType)) {
        throw new PersistImageError(`Invalid content type: ${contentType}. Only image files are allowed.`, 'INVALID_CONTENT_TYPE');
      }
    
      const fileName = getFilename(url, contentType);
      const filePersistPath = resolve(fullTargetPath, fileName);
      const writeStream = createWriteStream(filePersistPath);
      logger().info('fetchImage() fileName', { fileName, filePersistPath, writeStream });
    
      const [pipelineErr] = await tryCatch(pipeline(response.body, writeStream));
      logger().info('fetchImage() pipeline', { pipelineErr });
    
      if (pipelineErr != null) {
        throw new PersistImageError(`Failed to save file: ${pipelineErr.message}`, 'SAVE_FAILED');
      }
    
      const [fsStatErr, fileStats] = await tryCatch(fs.stat(filePersistPath));
      logger().info('fetchImage() fs.stat', { fsStatErr, fileStats });
      if (fsStatErr != null) {
        throw new PersistImageError(`Failed to get file stats: ${fsStatErr.message}`, 'STAT_FAILED');
      }
    
      return {
        filePersistPath,
        mimeType: contentType,
        size: fileStats.size,
      };
    }

Schema Changelog

Changes observed during successful MCP inspections.

  1. Changed2 schema fields changedv0.3.0
    • addedInput schema / $schema
      Added value: +"http://json-schema.org/draft-07/schema#"
    • addedInput schema / additionalProperties
      Added value: +false
  2. First observedv1.0.0

TDQS

A4.1/5.0
Behavior3/5

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

Without annotations, the description carries the full burden. It discloses a key behavior (auto-creation of targetPath), but does not mention what happens if the file already exists (overwrite?) or what occurs if the URL is invalid. This leaves important side effects unspecified.

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?

Two sentences, zero waste. The key information is front-loaded, and the conditional behavior follows naturally. No redundancy or filler.

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

Completeness3/5

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

The description covers the core operation and auto-creation, but omits details about how the image file is named (e.g., derived from URL) and potential error handling. Given the tool's simplicity and full schema coverage, these gaps could mislead an agent about the exact output.

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

Parameters4/5

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

Schema coverage is 100%, so baseline is 3. The description adds value beyond the schema by explicitly stating that targetPath need not pre-exist and will be created automatically. This clarifies the parameter's semantics beyond the schema's 'Folder where to save the image'.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

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

The description clearly states the action ('Store image at URL') and the destination ('folder relative to current workspace'), making the tool's purpose unambiguous. It distinguishes from sibling 'search_image' by focusing on persistence rather than discovery.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description gives clear context: it saves an image to a workspace-relative folder and automatically creates the target directory if missing. It does not explicitly mention alternatives or exclusions, but the 'relative to current workspace' and 'auto-create' instructions provide sufficient usage context for most cases.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Deploy Server

Other Tools