Skip to main content
Glama
JagjeevanAK

OpenFoodFacts-mcp

by JagjeevanAK

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

TableJSON Schema
NameRequiredDescriptionDefault
barcodeYes

Implementation Reference

  • 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');
      }
    }
  • 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 };
      }
    });
  • Schema: Defines the input schema for getProductByBarcode - expects a single 'barcode' string field using Zod validation.
    const barcodeSchema = { barcode: z.string() };
Behavior2/5

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

No annotations; description fails to mention response structure, error handling, or restrictions like rate limits. Minimal behavioral disclosure.

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?

Single sentence, no redundancy. Could be slightly expanded for clarity but remains appropriately concise.

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 simplicity, lacks definition of 'product details' and handling of invalid barcodes. Incomplete for agent decision-making.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Parameter 'barcode' has no description in schema (0% coverage). Description only repeats 'barcode (EAN/UPC)', adding no format or validation details.

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

Purpose5/5

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

Clearly states verb (Get product details) and resource (barcode). Specifies barcode type (EAN/UPC), differentiating from sibling tools like searchByBrand.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Indicates usage for exact barcode lookup but lacks explicit 'when not to use' or mention of alternative tools for partial searches.

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/JagjeevanAK/OpenFoodFacts-MCP'

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