Skip to main content
Glama

instacart_add_to_cart

Add grocery items to your Instacart cart by searching for products and selecting the first match. Specify product names and quantities to build your shopping list.

Instructions

Add a product to the Instacart cart. Searches for the product and adds the first matching result.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
productYesProduct name or search query
quantityNoQuantity to add (default: 1)

Implementation Reference

  • The actual implementation of addToCart function that performs browser automation to search for a product and add it to the Instacart cart. Handles product search, clicking add buttons, adjusting quantity, and retrieving cart count.
    export async function addToCart(productQuery: string, quantity: number = 1): Promise<{ success: boolean; message: string; cartCount?: number }> {
      const { page, context } = await initBrowser();
    
      try {
        // First search for the product
        const searchUrl = `${INSTACART_BASE_URL}/store/search/${encodeURIComponent(productQuery)}`;
        await page.goto(searchUrl, { waitUntil: "networkidle", timeout: DEFAULT_TIMEOUT });
    
        // Wait for results
        await page.waitForSelector('[data-testid="product-card"], .product-card, [class*="ProductCard"]', {
          timeout: 10000,
        });
    
        // Click on the first product's add button
        const addButton = await page.$('[data-testid="add-to-cart"], button:has-text("Add"), [class*="AddToCart"]');
        
        if (!addButton) {
          // Try clicking the product card itself first
          const productCard = await page.$('[data-testid="product-card"], .product-card, [class*="ProductCard"]');
          if (productCard) {
            await productCard.click();
            await page.waitForTimeout(1000);
            
            // Now look for add button on product detail page
            const detailAddButton = await page.waitForSelector(
              'button:has-text("Add to cart"), [data-testid="add-to-cart-button"]',
              { timeout: 5000 }
            ).catch(() => null);
            
            if (detailAddButton) {
              await detailAddButton.click();
            } else {
              throw new Error("Could not find add to cart button");
            }
          } else {
            throw new Error("No products found for query");
          }
        } else {
          await addButton.click();
        }
    
        await page.waitForTimeout(1000);
    
        // Handle quantity if more than 1
        if (quantity > 1) {
          for (let i = 1; i < quantity; i++) {
            const incrementButton = await page.$('[data-testid="increment-quantity"], button:has-text("+"), [aria-label*="increase"]');
            if (incrementButton) {
              await incrementButton.click();
              await page.waitForTimeout(300);
            }
          }
        }
    
        // Get current cart count
        const cartBadge = await page.$('[data-testid="cart-count"], .cart-badge, [class*="CartCount"]');
        const cartCountText = cartBadge ? await cartBadge.textContent() : null;
        const cartCount = cartCountText ? parseInt(cartCountText, 10) : undefined;
    
        await saveCookies(context);
    
        return {
          success: true,
          message: `Added ${quantity}x "${productQuery}" to cart`,
          cartCount,
        };
      } catch (error) {
        throw new Error(`Failed to add to cart: ${error instanceof Error ? error.message : String(error)}`);
      }
    }
  • The MCP tool handler for instacart_add_to_cart that receives the request parameters (product and quantity), calls the addToCart function from browser.ts, and formats the response.
    case "instacart_add_to_cart": {
      const { product, quantity = 1 } = args as {
        product: string;
        quantity?: number;
      };
    
      const result = await addToCart(product, quantity);
    
      return {
        content: [
          {
            type: "text",
            text: JSON.stringify(
              {
                success: result.success,
                message: result.message,
                cartCount: result.cartCount,
              },
              null,
              2
            ),
          },
        ],
      };
    }
  • Tool registration and schema definition for instacart_add_to_cart in the ListToolsRequestSchema handler. Defines the tool name, description, and input parameters (product: string, quantity: number).
    {
      name: "instacart_add_to_cart",
      description:
        "Add a product to the Instacart cart. Searches for the product and adds the first matching result.",
      inputSchema: {
        type: "object",
        properties: {
          product: {
            type: "string",
            description: "Product name or search query",
          },
          quantity: {
            type: "number",
            description: "Quantity to add (default: 1)",
          },
        },
        required: ["product"],
      },
    },

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/markswendsen-code/mcp-instacart'

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