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
| Name | Required | Description | Default |
|---|---|---|---|
| count | No | Number of results to return (1-10, default: 2) | |
| query | Yes | Search query for images | |
| safe | No | Safe search setting (default: off) | |
| startIndex | No | Starting index of next search result page (not needed for initial search request) |
Implementation Reference
- src/tools/search_image/index.ts:17-87 (handler)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}`, })), ], }; }; - src/tools/search_image/index.ts:8-13 (schema)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(); }