searchProducts
Search for food products by name, brand, or category to access detailed nutritional data from the Open Food Facts database.
Instructions
Search products by name, brand, or category
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| query | Yes | ||
| page | No | ||
| pageSize | No |
Implementation Reference
- src/tools/product-search.ts:35-110 (handler)The actual implementation of the searchProducts function. Queries the Open Food Facts search API (world.openfoodfacts.org/cgi/search.pl) with search_terms, page, page_size, and json parameters. Handles barcode queries as a special case by looking up the product directly first. Returns a SearchProductsResult with mapped products and pagination info.
export async function searchProducts(query: string, page: number = 1, pageSize: number = 20): Promise<SearchProductsResult> { try { // Check if the query looks like a barcode (8-14 digits) const isBarcode = /^[0-9]{8,14}$/.test(query.trim()); if (isBarcode) { // If it's a barcode, use the direct product lookup API first try { const product = await getProductByBarcode(query.trim()); // Convert the single product to the expected search results format return { products: [{ id: product.id, name: product.name, brand: product.brands || 'Unknown brand', barcode: product.barcode, imageUrl: product.imageUrl || '', nutriScore: product.nutriScore || '', ingredients: product.ingredients || '', categories: product.categories || '' }], count: 1, page: 1, pageSize: 1, pageCount: 1 }; } catch (barcodeError) { logger.info(`Barcode lookup failed for ${query}, falling back to search API: ${barcodeError}`); // If direct lookup fails, fall back to regular search } } // For general text search, use fetch directly with the search API // The SDK doesn't expose search_terms parameter in its TypeScript types const searchUrl = new URL('https://world.openfoodfacts.org/cgi/search.pl'); searchUrl.searchParams.set('search_terms', query); searchUrl.searchParams.set('page', page.toString()); searchUrl.searchParams.set('page_size', pageSize.toString()); searchUrl.searchParams.set('json', '1'); const response = await fetch(searchUrl.toString()); if (!response.ok) { throw new Error(`API error: ${response.status} - ${response.statusText}`); } const data = await response.json(); // Check if the response is valid if (!data || !Array.isArray(data.products)) { throw new Error('Invalid response from Open Food Facts API'); } // Return the products from the response with pagination info return { products: data.products.map((product: any): SearchProductItem => ({ id: product.id || product._id, name: product.product_name || 'Unknown product', brand: product.brands || 'Unknown brand', barcode: product.code || '', imageUrl: product.image_url || '', nutriScore: product.nutriscore_grade || '', ingredients: product.ingredients_text || '', categories: product.categories || '' })), count: data.count || 0, page, pageSize, pageCount: Math.ceil((data.count || 0) / pageSize) } as SearchProductsResult; } catch (error) { logger.error('Error searching products:', error); throw new Error(`Failed to search products: ${error instanceof Error ? error.message : String(error)}`); } } - src/tools/product-search.ts:7-26 (schema)Type definitions for the searchProducts tool: SearchProductItem interface (id, name, brand, barcode, imageUrl, nutriScore, ingredients, categories) and SearchProductsResult interface (products array, count, page, pageSize, pageCount).
// Interface for the mapped product in search results export interface SearchProductItem { id: string; name: string; brand: string; barcode: string; imageUrl: string; nutriScore: string; ingredients: string; categories: string; } // Interface for the return value of searchProducts function export interface SearchProductsResult { products: SearchProductItem[]; count: number; page: number; pageSize: number; pageCount: number; } - src/tools/index.ts:48-68 (registration)Registration of the 'searchProducts' tool with the MCP server via server.registerTool. Defines the description ('Search products by name, brand, or category'), input schema (query: string, page: number with default 1, pageSize: number with default 10), and the handler callback that calls the imported searchProducts function and serializes the result as JSON.
const searchSchema = { query: z.string(), page: z.number().default(1), pageSize: z.number().default(10) }; const barcodeSchema = { barcode: z.string() }; const productSchema = { nameOrBarcode: z.string() }; const compareSchema = { nameOrBarcode1: z.string(), nameOrBarcode2: z.string() }; /** * Register all MCP tools with the server */ export function registerTools(server: McpServer): void { server.registerTool('searchProducts', { description: 'Search products by name, brand, or category', inputSchema: searchSchema }, async ({ query, page, pageSize }) => { try { const results = await searchProducts(query, page ?? 1, pageSize ?? 10); return { content: [{ type: 'text' as const, text: JSON.stringify(results) }] }; } catch (error: any) { return { content: [{ type: 'text' as const, text: `Error: ${error.message}` }], isError: true }; } }); - src/tools/index.ts:18-45 (helper)The findProduct helper function (in index.ts) that uses searchProducts to look up a product by name. It calls searchProducts(query, 1, 1) to get the first matching result, then fetches full details via getProductByBarcode.
async function findProduct(nameOrBarcode: string): Promise<any> { if (!nameOrBarcode?.trim()) return null; const query = nameOrBarcode.trim(); const isBarcode = /^\d+$/.test(query); if (isBarcode) { try { const product = await getProductByBarcode(query); if (product) return { product }; } catch (error) { logger.error(`Barcode lookup failed: ${error}`); } } try { const results = await searchProducts(query, 1, 1); const barcode = results?.products?.[0]?.barcode; if (barcode) { const product = await getProductByBarcode(barcode); return { product }; } } catch (error) { logger.error(`Search failed: ${error}`); } return null; } - src/tools/helpers.ts:26-49 (helper)An alternative findProduct helper (in helpers.ts) that also uses searchProducts(query, 1, 1) to find a product by name, then retrieves full details via getProductByBarcode. Used by other tools (e.g., analyzeProduct) to resolve product names.
export async function findProduct(nameOrBarcode: string): Promise<any> { if (!nameOrBarcode?.trim()) return null; const query = nameOrBarcode.trim(); const isBarcode = /^\d+$/.test(query); if (isBarcode) { try { return await getProductByBarcode(query); } catch (error) { logger.error(`Barcode lookup failed: ${error}`); } } // Search by name and get first result try { const results = await searchProducts(query, 1, 1); const barcode = results?.products?.[0]?.barcode; if (barcode) { return await getProductByBarcode(barcode); } } catch (error) { logger.error(`Search failed: ${error}`); }