Multi-Step Actions

Create tools that perform complex actions with validation and feedback.

Pattern: Validate → Act → Confirm

import '@mcp-b/global';
navigator.modelContext.registerTool({
name: 'add_to_cart',
description: 'Add a product to the shopping cart',
inputSchema: {
type: 'object',
properties: {
productId: { type: 'string', description: 'The product ID to add' },
quantity: { type: 'number', description: 'Quantity to add' },
},
required: ['productId'],
},
execute: async ({ productId, quantity = 1 }) => {
// 1. Find the product
const product = document.querySelector(`[data-product-id="${productId}"]`);
if (!product) {
return { content: [{ type: 'text', text: `Product ${productId} not found` }] };
}
const productName = product.querySelector('.product-name')?.textContent;
// 2. Check stock
if (product.querySelector('.out-of-stock')) {
return { content: [{ type: 'text', text: `${productName} is out of stock` }] };
}
// 3. Click add to cart
const addButton = product.querySelector<HTMLButtonElement>('.add-to-cart');
if (!addButton) {
return { content: [{ type: 'text', text: 'Add to cart button not found' }] };
}
addButton.click();
// 4. Wait for cart update
await new Promise((resolve) => setTimeout(resolve, 300));
// 5. Confirm success
return {
content: [{ type: 'text', text: `Added ${quantity}x ${productName} to cart` }],
};
},
});

Error Handling Best Practices

  1. Validate inputs early — Check if elements exist before acting
  2. Provide clear error messages — Tell the agent what went wrong
  3. Include context — Return relevant data even on failure
  4. Handle async operations — Wait for UI updates when needed

Try it

Create an “add to cart” tool for the product list. Handle the case where the product is out of stock. Ask the agent “Add the Wireless Mouse to cart.”

Powered by WebContainers
Files
Preparing Environment
  • npm install
  • npm run dev