Reading Data from the Page
Create tools that read structured data from the DOM.
Pattern: Query and Extract
import '@mcp-b/global';
navigator.modelContext.registerTool({ name: 'get_products', description: 'Get the list of products displayed on the page', inputSchema: { type: 'object', properties: {}, }, execute: 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 { content: [{ type: 'text', text: JSON.stringify(products, null, 2) }], }; },});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 properties object:
inputSchema: { type: 'object', properties: {},}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