getProductByBarcode
Fetch food product details by scanning or entering a barcode. Retrieve ingredients, nutrition, and more from the world's largest open food database.
Instructions
Get product details by barcode (EAN/UPC)
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| barcode | Yes |
Implementation Reference
- src/tools/product-search.ts:117-166 (handler)Core handler: Fetches product details from Open Food Facts V3 API by barcode (8-14 digits), validates format, and returns structured product data including nutrition facts, ingredients, allergens, and more.
export async function getProductByBarcode(barcode: string) { try { // Validate barcode format if (!barcode.match(/^[0-9]{8,14}$/)) { throw new Error('Invalid barcode format. Expected 8-14 digits.'); } // Use the SDK's getProduct method (V3 API) - using 'all' to get all fields const result = await client.getProductV3(barcode, { fields: ['all'] }); // Check if product was found - check for error or no data if (result.error || !result.data || result.data.status === 'failure') { throw new Error(`Product with barcode ${barcode} not found`); } // Cast to any for easier access to fields since the SDK typing is complex const product: any = result.data; // Return the product information with selected fields return { id: product._id || barcode, barcode: product.code || barcode, name: product.product_name || 'Unknown product', brands: product.brands, ingredients: product.ingredients_text, allergens: product.allergens, nutriScore: product.nutriscore_grade, novaGroup: product.nova_group, imageUrl: product.selected_images?.front?.display?.en || product.image_url || '', nutritionFacts: { energy: product.nutriments?.['energy-kcal_100g'], fat: product.nutriments?.fat_100g, saturatedFat: product.nutriments?.['saturated-fat_100g'], carbohydrates: product.nutriments?.carbohydrates_100g, sugars: product.nutriments?.sugars_100g, fiber: product.nutriments?.fiber_100g, proteins: product.nutriments?.proteins_100g, salt: product.nutriments?.salt_100g }, labels: product.labels, categories: product.categories, countries: product.countries }; } catch (error) { logger.error('Error fetching product:', error); throw new Error(error instanceof Error ? error.message : 'Failed to get product details'); } } - src/tools/index.ts:70-80 (registration)Registration: Registers the 'getProductByBarcode' MCP tool with input schema ('barcode' as z.string()) and an async handler that calls the core function and returns JSON-serialized product data.
server.registerTool('getProductByBarcode', { description: 'Get product details by barcode (EAN/UPC)', inputSchema: barcodeSchema }, async ({ barcode }) => { try { const product = await getProductByBarcode(barcode); return { content: [{ type: 'text' as const, text: JSON.stringify(product) }] }; } catch (error: any) { return { content: [{ type: 'text' as const, text: `Error: ${error.message}` }], isError: true }; } }); - src/tools/index.ts:49-49 (schema)Schema: Defines the input schema for getProductByBarcode - expects a single 'barcode' string field using Zod validation.
const barcodeSchema = { barcode: z.string() };