Reading Data from the Page

Create tools that read structured data from the DOM.

Pattern: Query and Extract

import { useWebMCP } from '@mcp-b/react-webmcp';
import { z } from 'zod';
function useProductsTool() {
useWebMCP({
name: 'get_products',
description: 'Get the list of products displayed on the page',
inputSchema: {},
handler: async () => {
const products = Array.from(
document.querySelectorAll('.product-card')
).map((card) => ({
id: card.getAttribute('data-product-id'),
name: card.querySelector('.product-name')?.textContent?.trim(),
price: card.querySelector('.product-price')?.textContent?.trim(),
inStock: card.querySelector('.out-of-stock') === null,
}));
return {
success: true,
products,
message: `Found ${products.length} products`,
};
},
});
}

Key Techniques

  1. Use data-* attributes for IDs and metadata
  2. Trim whitespace from text content
  3. Check for element existence with optional chaining
  4. Return structured JSON for the agent to understand

Empty Input Schema

When a tool takes no parameters, use an empty object:

inputSchema: {},

Try it

The app displays a product list. Create a tool to read and return the product data. Ask the agent “What products are available?”

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