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();
    }
Behavior2/5

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

No annotations exist, and the description does not disclose behavioral details such as whether the tool performs side effects, requires authentication, or has rate limits. The description only says 'search', which is insufficient without annotations.

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

Conciseness3/5

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

The description is a single short sentence, which is concise but lacks structure and detail. It is not verbose, but it could be more informative without being overly long.

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?

Given the lack of output schema and annotations, the description should provide more context about return values, error handling, or usage examples. It does not, leaving the agent with minimal guidance.

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?

The input schema provides 100% description coverage for all four parameters, so the baseline is 3. The description adds no additional meaning beyond what is already in the schema.

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 states the verb 'search' and resource 'image(s) online', but lacks specificity about what is returned (e.g., URLs, metadata) and does not differentiate from the sibling tool 'persist_image', which likely handles storage.

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?

No guidance is provided on when to use this tool versus the sibling tool 'persist_image' or any other alternatives. The description does not mention context or prerequisites.

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

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/srigi/mcp-google-images-search'

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