1

Get your Browserbase API Key

Go over the Dashboard’s Settings tab:

Then copy your API Key directly from the input and set the BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID environment variables.

2

Get your OpenAI API Key

Create an OpenAI account and get your API key from the OpenAI platform.

Set the environment variable:

export OPENAI_API_KEY=your_openai_api_key
3

Create a new project

Initialize a new Node.js project:

mkdir mastra-web-agent
cd mastra-web-agent
npm init -y
4

Install dependencies

Install the required packages:

npm install @mastra/core @mastra/memory mastra @ai-sdk/openai @browserbasehq/stagehand zod
npm install -D @types/node tsx typescript
5

Create the Stagehand tools

Create src/mastra/tools/index.ts with the web automation tools:

src/mastra/tools/index.ts
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
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
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',
  }),
});
8

Configure Environment

Create a .env file in the project root:

.env
BROWSERBASE_API_KEY=your_browserbase_api_key
BROWSERBASE_PROJECT_ID=your_browserbase_project_id
OPENAI_API_KEY=your_openai_api_key
9

Start the Agent

Add to your package.json:

package.json
{
  "scripts": {
    "dev": "mastra dev"
  }
}

Run the development server:

npm run dev

This starts the Mastra interface where you can interact with your web automation agent.

How It Works

The integration provides three main tools for your AI agent:

  • Act: Perform actions like clicking buttons or filling forms
  • Observe: Find and identify elements on web pages
  • Extract: Pull structured data from websites

Try these Commands

Once your agent is running, try these natural language instructions:

"Go to example.com and find the contact button"
"Navigate to a news website and extract the main headlines"
"Search for 'AI automation' on Google"
"Extract product prices from an e-commerce site"

The agent will automatically choose the right tools and execute the web automation tasks.

Example Agent on GitHub

Find the sample project for this integration

Next Steps

  • 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.