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

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observedv1.1.0

TDQS

A3.8/5.0
Behavior2/5

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

No annotations are provided, so the description must carry the behavioral disclosure burden. It states 'Get product details' implying a read operation, but omits details like what specific fields are returned, potential rate limits, authentication requirements, or data source freshness.

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

Conciseness5/5

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

The description is a single, short sentence with no extraneous words. It is front-loaded and efficient, earning its place.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a simple lookup tool with one parameter and no output schema, the description is adequate. However, adding context about the return value (e.g., 'including name, brand, and nutrition') would improve completeness without being verbose.

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

Parameters4/5

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

The schema has 0% description coverage for the barcode parameter. The description adds meaning by specifying the barcode format (EAN/UPC), which helps an agent know what to input. However, it does not include examples or validation rules, so it's not a 5.

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?

The description 'Get product details by barcode (EAN/UPC)' clearly states the action (get), the resource (product details), and the specific identifier (barcode with formats EAN/UPC). It distinguishes from siblings like searchProducts which search by name.

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?

The description implies usage when you have a barcode, but provides no explicit guidance on when not to use it (e.g., for non-barcode queries) or alternatives. Siblings like searchProducts exist, but no comparative context.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.