Create src/mastra/tools/index.ts with the web automation tools:
src/mastra/tools/index.ts
Copy
Ask AI
import { createTool } from '@mastra/core/tools';import { z } from 'zod';import { Stagehand } from "@browserbasehq/stagehand";export const stagehandActTool = createTool({ id: 'web-act', description: 'Take an action on a webpage using Stagehand', inputSchema: z.object({ url: z.string().optional().describe('URL to navigate to (optional if already on a page)'), action: z.string().describe('Action to perform (e.g., "click sign in button", "type hello in search field")'), }), outputSchema: z.object({ success: z.boolean(), message: z.string(), }), execute: async ({ context }) => { const stagehand = await sessionManager.ensureStagehand(); const page = stagehand.page; try { if (context.url) { await page.goto(context.url); } if (context.action) { await page.act(context.action); } return { success: true, message: `Successfully performed: ${context.action}` }; } catch (error: any) { throw new Error(`Stagehand action failed: ${error.message}`); } },});export const stagehandObserveTool = createTool({ id: 'web-observe', description: 'Observe elements on a webpage using Stagehand to plan actions', inputSchema: z.object({ url: z.string().optional().describe('URL to navigate to (optional if already on a page)'), instruction: z.string().describe('What to observe (e.g., "find the sign in button")'), }), outputSchema: z.array(z.any()).describe('Array of observable actions'), execute: async ({ context }) => { const stagehand = await sessionManager.ensureStagehand(); const page = stagehand.page; try { if (context.url) { await page.goto(context.url); } return await page.observe(context.instruction); } catch (error: any) { throw new Error(`Stagehand observation failed: ${error.message}`); } },});export const stagehandExtractTool = createTool({ id: 'web-extract', description: 'Extract data from a webpage using Stagehand', inputSchema: z.object({ url: z.string().optional().describe('URL to navigate to (optional if already on a page)'), instruction: z.string().describe('What to extract (e.g., "extract all product prices")'), schema: z.record(z.any()).optional().describe('Zod schema definition for data extraction'), }), outputSchema: z.any().describe('Extracted data according to schema'), execute: async ({ context }) => { const stagehand = await sessionManager.ensureStagehand(); const page = stagehand.page; try { if (context.url) { await page.goto(context.url); } const defaultSchema = { content: z.string() }; return await page.extract({ instruction: context.instruction, schema: z.object(context.schema || defaultSchema) }); } catch (error: any) { throw new Error(`Stagehand extraction failed: ${error.message}`); } },});
6
Create the web agent
Create src/mastra/agents/index.ts:
src/mastra/agents/index.ts
Copy
Ask AI
import { openai } from '@ai-sdk/openai';import { Agent } from '@mastra/core/agent';import { stagehandActTool, stagehandObserveTool, stagehandExtractTool } from '../tools';import { Memory } from '@mastra/memory';const memory = new Memory();export const webAgent = new Agent({ name: 'Web Assistant', instructions: ` You are a helpful web assistant that can navigate websites and extract information. Use the stagehandActTool to perform actions on webpages. Use the stagehandObserveTool to find elements on webpages. Use the stagehandExtractTool to extract data from webpages. `, model: openai('gpt-4o'), tools: { stagehandActTool, stagehandObserveTool, stagehandExtractTool }, memory: memory});
7
Initialize Mastra
Create src/mastra/index.ts:
src/mastra/index.ts
Copy
Ask AI
import { Mastra } from '@mastra/core/mastra';import { createLogger } from '@mastra/core/logger';import { webAgent } from './agents';export const mastra = new Mastra({ agents: { webAgent }, logger: createLogger({ name: 'Mastra', level: 'info', }),});
Custom Instructions: Modify the agent’s behavior in src/mastra/agents/index.ts
Add Tools: Create additional tools for specific automation needs
Production Setup: Add proper error handling and logging for production use
You now have a fully functional AI agent that can automate web tasks through natural language! Learn more about advanced features in the Mastra documentation.