Skip to main content
Glama
CupOfOwls

Kroger MCP Server

add_items_to_cart

Add grocery items to your Kroger cart for pickup or delivery by specifying product IDs and quantities.

Instructions

    Add a single item to the user's Kroger cart and track it locally.
    
    If the user doesn't specifically indicate a preference for pickup or delivery,
    you should ask them which modality they prefer before calling this tool.
    
    Args:
        product_id: The product ID or UPC to add to cart
        quantity: Quantity to add (default: 1)
        modality: Fulfillment method - PICKUP or DELIVERY
    
    Returns:
        Dictionary confirming the item was added to cart
    

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
product_idYes
quantityNo
modalityNoPICKUP

Implementation Reference

  • Core handler for the 'add_items_to_cart' tool. Handles API call to Kroger cart.add_to_cart and local tracking update. Includes input validation via types and comprehensive error handling.
    @mcp.tool()
    async def add_items_to_cart(
        product_id: str,
        quantity: int = 1,
        modality: str = "PICKUP",
        ctx: Context = None
    ) -> Dict[str, Any]:
        """
        Add a single item to the user's Kroger cart and track it locally.
        
        If the user doesn't specifically indicate a preference for pickup or delivery,
        you should ask them which modality they prefer before calling this tool.
        
        Args:
            product_id: The product ID or UPC to add to cart
            quantity: Quantity to add (default: 1)
            modality: Fulfillment method - PICKUP or DELIVERY
        
        Returns:
            Dictionary confirming the item was added to cart
        """
        try:
            if ctx:
                await ctx.info(f"Adding {quantity}x {product_id} to cart with {modality} modality")
            
            # Get authenticated client
            client = get_authenticated_client()
            
            # Format the item for the API
            cart_item = {
                "upc": product_id,
                "quantity": quantity,
                "modality": modality
            }
            
            if ctx:
                await ctx.info(f"Calling Kroger API to add item: {cart_item}")
            
            # Add the item to the actual Kroger cart
            # Note: add_to_cart returns None on success, raises exception on failure
            client.cart.add_to_cart([cart_item])
            
            if ctx:
                await ctx.info("Successfully added item to Kroger cart")
            
            # Add to local cart tracking
            _add_item_to_local_cart(product_id, quantity, modality)
            
            if ctx:
                await ctx.info("Item added to local cart tracking")
            
            return {
                "success": True,
                "message": f"Successfully added {quantity}x {product_id} to cart",
                "product_id": product_id,
                "quantity": quantity,
                "modality": modality,
                "timestamp": datetime.now().isoformat()
            }
            
        except Exception as e:
            if ctx:
                await ctx.error(f"Failed to add item to cart: {str(e)}")
            
            # Provide helpful error message for authentication issues
            error_message = str(e)
            if "401" in error_message or "Unauthorized" in error_message:
                return {
                    "success": False,
                    "error": "Authentication failed. Please run force_reauthenticate and try again.",
                    "details": error_message
                }
            elif "400" in error_message or "Bad Request" in error_message:
                return {
                    "success": False,
                    "error": f"Invalid request. Please check the product ID and try again.",
                    "details": error_message
                }
            else:
                return {
                    "success": False,
                    "error": f"Failed to add item to cart: {error_message}",
                    "product_id": product_id,
                    "quantity": quantity,
                    "modality": modality
                }
  • Registration point where cart_tools.register_tools(mcp) is called, which defines and registers the add_items_to_cart tool using @mcp.tool() decorator.
    # Register all tools from the modules
    location_tools.register_tools(mcp)
    product_tools.register_tools(mcp)
    cart_tools.register_tools(mcp)
    info_tools.register_tools(mcp)
    profile_tools.register_tools(mcp)
    utility_tools.register_tools(mcp)
    auth_tools.register_tools(mcp)
  • Helper function called by the handler to persist cart items to local JSON file (kroger_cart.json), merging quantities for duplicate product/modality.
    def _add_item_to_local_cart(product_id: str, quantity: int, modality: str, product_details: Dict[str, Any] = None) -> None:
        """Add an item to the local cart tracking"""
        cart_data = _load_cart_data()
        current_cart = cart_data.get("current_cart", [])
        
        # Check if item already exists in cart
        existing_item = None
        for item in current_cart:
            if item.get("product_id") == product_id and item.get("modality") == modality:
                existing_item = item
                break
        
        if existing_item:
            # Update existing item quantity
            existing_item["quantity"] = existing_item.get("quantity", 0) + quantity
            existing_item["last_updated"] = datetime.now().isoformat()
        else:
            # Add new item
            new_item = {
                "product_id": product_id,
                "quantity": quantity,
                "modality": modality,
                "added_at": datetime.now().isoformat(),
                "last_updated": datetime.now().isoformat()
            }
            
            # Add product details if provided
            if product_details:
                new_item.update(product_details)
            
            current_cart.append(new_item)
        
        cart_data["current_cart"] = current_cart
        cart_data["last_updated"] = datetime.now().isoformat()
        _save_cart_data(cart_data)
  • Input schema from function signature and docstring: product_id (str, required), quantity (int, default 1), modality (str, default PICKUP), returns success dict.
    async def add_items_to_cart(
        product_id: str,
        quantity: int = 1,
        modality: str = "PICKUP",
        ctx: Context = None
Behavior3/5

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

With no annotations provided, the description carries the full burden. It discloses that the tool 'track[s] it locally', which adds behavioral context beyond the basic action. However, it doesn't cover important aspects like error handling, authentication requirements (implied by sibling tools like 'complete_authentication'), or whether this is a mutation (implied by 'add').

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 well-structured and front-loaded with the core purpose. Each sentence earns its place: the first states the action, the second provides usage guidance, and the Args/Returns sections efficiently document parameters and output. No wasted words.

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

Completeness3/5

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

For a 3-parameter mutation tool with no annotations and no output schema, the description is adequate but has gaps. It covers parameters well and gives usage guidance, but lacks details on authentication (implied by sibling tools), error cases, or the structure of the return dictionary. The 'track it locally' hint adds some context.

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?

Schema description coverage is 0%, so the description must compensate. It adds meaningful semantics for all three parameters: 'product_id' is explained as 'The product ID or UPC', 'quantity' as 'Quantity to add (default: 1)', and 'modality' as 'Fulfillment method - PICKUP or DELIVERY'. This significantly enhances understanding beyond the bare schema.

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 action ('Add a single item to the user's Kroger cart') and resource ('cart'), distinguishing it from bulk operations and other cart-related tools like 'remove_from_cart' or 'view_current_cart'. However, it doesn't explicitly differentiate from 'bulk_add_to_cart' beyond mentioning 'single item'.

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

Usage Guidelines4/5

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

The description provides explicit guidance on when to use this tool ('If the user doesn't specifically indicate a preference for pickup or delivery, you should ask them which modality they prefer before calling this tool'), which is helpful for the agent. It doesn't mention alternatives like 'bulk_add_to_cart' or prerequisites, but the context is clear.

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/CupOfOwls/kroger-mcp'

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