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}`);
        }
Behavior2/5

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

No annotations are provided, so the description carries full burden for behavioral disclosure. It only states 'Search products' without mentioning pagination behavior (despite page and pageSize in schema), result format, or any side effects. The description fails to convey important behavioral traits.

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?

The description is a single short sentence, making it concise. However, the conciseness comes at the cost of omitting necessary details, so it is not an optimal balance.

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 presence of many sibling search tools and three parameters (one required), the description is too minimal. It does not explain how the query parameter works, what results are returned, or how pagination functions. The lack of an output schema increases the need for a comprehensive description.

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

Parameters1/5

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

Input schema has 0% description coverage for parameters, and the description does not explain the 'query' parameter or how it maps to the mentioned fields (name, brand, category). The default values for page and pageSize are not elaborated. The description adds no meaning beyond the schema structure.

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 verb 'Search' and the resource 'products', and specifies the searchable fields (name, brand, or category). This distinguishes it from sibling tools like searchByBrand and searchByCategory, which are more specific. However, it could be more explicit about combining multiple fields.

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 provides no guidance on when to use this tool versus alternatives such as advancedSearch, searchByBrand, or searchByCategory. There is no mention of use cases, prerequisites, or exclusions, leaving the agent without context for selection.

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