Skip to main content
Glama
JagjeevanAK

OpenFoodFacts-mcp

by JagjeevanAK

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

TableJSON Schema
NameRequiredDescriptionDefault
queryYes
pageNo
pageSizeNo

Implementation Reference

  • 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)}`);
      }
    }
  • 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;
    }
  • 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 };
        }
      });
  • 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;
    }
  • 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}`);
        }

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observedv1.1.0

TDQS

C2.6/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 disclose behavioral traits. It only states the search purpose without mentioning pagination behavior, authentication needs, or result limitations. This is inadequate for a tool with no annotation coverage.

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

Conciseness3/5

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

The description is very concise at 6 words, but it misses critical information like pagination and parameter details. While not verbose, it is under-specified, which reduces its effectiveness for an AI agent.

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 the tool has 3 parameters, no output schema, and many sibling tools, the description is incomplete. It fails to explain how it differs from other search tools, does not describe the return format, and omits pagination behavior.

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?

Schema description coverage is 0%, so the description should add meaning beyond parameter names. It mentions query by name/brand/category but ignores page and pageSize parameters, which are not self-explanatory in terms of their purpose and defaults.

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

Purpose4/5

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

The description clearly states the tool searches products by name, brand, or category, providing a specific verb and resource. However, it does not differentiate from sibling tools like searchByBrand or searchByCategory, which are more targeted.

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

Usage Guidelines2/5

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

The description offers no guidance on when to use this tool versus alternatives. With 20 sibling tools including advancedSearch and specific brand/category searches, the lack of usage context is a significant gap.

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