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
- Use
data-*attributes for IDs and metadata - Trim whitespace from text content
- Check for element existence with optional chaining
- 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?”
Files
Preparing Environment
- npm install
- npm run dev