Skip to main content
Glama
srigi

Google Images Search MCP

by srigi

search_image

Search for images online using a query. Returns up to 10 results with adjustable safe search and pagination.

Instructions

Search the image(s) online

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
countNoNumber of results to return (1-10, default: 2)
queryYesSearch query for images
safeNoSafe search setting (default: off)
startIndexNoStarting index of next search result page (not needed for initial search request)

Implementation Reference

  • The handler function that executes the 'search_image' tool logic. It receives query, count, safe, startIndex parameters, calls searchImages() utility, and formats the response with image links, metadata, and pagination info.
    export const handler: ToolCallback<typeof schema> = async ({ count = 2, query, safe = 'off', startIndex }) => {
      logger().info('handler called', { count, query, safe, startIndex });
    
      const [err, res] = await tryCatch<GoogleSearchError, SearchResult>(searchImages({ count, query, safe, startIndex }));
      if (err != null) {
        return {
          _meta: {
            error: {
              type: 'GoogleSearchError',
              message: err.message,
              status: err.status,
              statusText: err.statusText,
            },
          },
          content: [
            {
              type: 'text' as const,
              text: `Error: ${err.message}`,
            },
          ],
        };
      }
    
      const _meta = {
        itemsCount: res.items.length,
        nextPageIdx: res.nextPageIdx,
        previousPageIdx: res.previousPageIdx,
        searchTerms: res.searchTerms,
      };
      const result = {
        summary: {
          query: res.searchTerms,
          itemsReturned: res.items.length,
          pagination: {
            previousPageStartIndex: res.previousPageIdx,
            nextPageStartIndex: res.nextPageIdx,
          },
        },
        items: res.items.map((item, index) => ({
          index: index + (startIndex || 1),
          title: item.title,
          link: item.link,
          displayLink: item.displayLink,
          mimeType: item.mime,
          image: {
            contextLink: item.image.contextLink,
            dimensions: `${item.image.width}x${item.image.height}`,
            size: `${Math.round(item.image.byteSize / 1024)}KB`,
            thumbnail: {
              link: item.image.thumbnailLink,
              dimensions: `${item.image.thumbnailWidth}x${item.image.thumbnailHeight}`,
            },
          },
        })),
      };
      logger().info('handler success', { _meta, result });
    
      return {
        _meta,
        content: [
          {
            type: 'text' as const,
            text: `Search successfully returned ${count} images. StartIndex of the next search page is: ${result.summary.pagination.nextPageStartIndex}`,
          },
          ...result.items.map((i) => ({
            type: 'text' as const,
            text: `${i.index}: ${i.link}`,
          })),
        ],
      };
    };
  • Zod schema defining input validation for the search_image tool: query (string), count (number 1-10, optional default 2), safe (enum off/medium/high, optional), startIndex (number, optional).
    export const schema = {
      count: z.number().min(1).max(10).optional().describe('Number of results to return (1-10, default: 2)'),
      query: z.string().describe('Search query for images'),
      safe: z.enum(['off', 'medium', 'high']).optional().describe('Safe search setting (default: off)'),
      startIndex: z.number().min(1).optional().describe('Starting index of next search result page (not needed for initial search request)'),
    } as const;
  • src/index.ts:20-20 (registration)
    Registration of the 'search_image' tool on the MCP server with its schema and handler.
    server.tool('search_image', 'Search the image(s) online', searchImageSchema, searchImageHandler);
  • The searchImages() utility function that calls the Google Custom Search API to fetch images. Builds the URL, fetches data, validates the response with Zod, extracts pagination info, and returns SearchResult.
    export async function searchImages({ count = 2, query, safe = 'off', startIndex }: SearchOptions): Promise<SearchResult> {
      const url = buildSearchUrl({ query, count, safe, startIndex });
      logger().info('searchImages() called', { count, query, safe, startIndex, url });
    
      const response = await fetch(url);
      if (!response.ok) {
        throw new GoogleSearchError(`Google Search API request failed: ${response.statusText}`, response.status, response.statusText);
      }
    
      const data = await response.json();
      logger().info('searchImages() response data', { data });
    
      const [validationErr, validatedData] = tryCatch(() => googleSearchResponseSchema.parse(data));
      if (validationErr != null) {
        throw new GoogleSearchError(`Invalid response format from Google Search API: ${validationErr.message}`);
      }
    
      // extract pagination information
      const requestQuery = validatedData.queries.request[0];
      const previousPageIdx = validatedData.queries.previousPage?.[0]?.startIndex;
      const nextPageIdx = validatedData.queries.nextPage?.[0]?.startIndex;
    
      return {
        items: validatedData.items || [],
        previousPageIdx,
        nextPageIdx,
        searchTerms: requestQuery.searchTerms,
      };
    }
  • buildSearchUrl() helper that constructs the Google Custom Search API URL with cx (engine ID), key (API key), num, q, searchType=image, safe, and start parameters.
    export function buildSearchUrl({ count, query, safe, startIndex }: SearchOptions): string {
      const url = new URL('https://www.googleapis.com/customsearch/v1');
      url.searchParams.append('cx', env.SEARCH_ENGINE_ID);
      url.searchParams.append('key', env.API_KEY);
      url.searchParams.append('num', count.toString());
      url.searchParams.append('q', query);
      url.searchParams.append('searchType', 'image');
    
      if (safe != null) {
        url.searchParams.append('safe', safe);
      }
      if (startIndex != null) {
        url.searchParams.append('start', startIndex.toString());
      }
    
      return url.toString();
    }

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

C2.5/5.0
Behavior2/5

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

With no annotations, the description carries the full burden of behavioral disclosure. It does not mention safe search settings, pagination, result limits, or any side effects. The agent is left unaware of how the search behaves or what the response contains.

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

Conciseness4/5

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

The description is a single short sentence with no wasted words. It is front-loaded with the core action, but it is too sparse to be truly helpful, making it concise but under-specified.

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 tool has 4 parameters and no output schema, the description is severely incomplete. It fails to mention the result format, pagination behavior, or safe search implications, leaving critical gaps for an agent to invoke and interpret the tool correctly.

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 input schema fully documents all parameters. The description adds no semantic detail beyond the schema, but the baseline of 3 applies because the schema carries the burden effectively.

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

Purpose3/5

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

The description 'Search the image(s) online' identifies a clear verb and resource, but it is vague about the scope and output. It does not differentiate from the sibling tool 'persist_image' beyond the search action, and 'online' adds little specificity.

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?

There is no guidance on when to use this tool versus alternatives. The sibling 'persist_image' exists, but the description does not mention any selection criteria or exclusions, leaving the agent without context for choosing this tool.

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