跳到主要内容
非官方简体中文翻译,内容版权归 Mastra 所有,遵循 Apache-2.0 许可。

MastraBrowser class

The MastraBrowser class is the abstract base class for browser automation providers. Its common interface covers browser launch and thread isolation, plus screencast streaming and input events.

You don't instantiate MastraBrowser directly. Instead, use a provider implementation:

Usage example
Usage example的直接链接

src/mastra/agents/index.ts
import { Agent } from '@mastra/core/agent'
import { AgentBrowser } from '@mastra/agent-browser'

const browser = new AgentBrowser({
headless: true,
viewport: { width: 1280, height: 720 },
scope: 'thread',
})

export const browserAgent = new Agent({
id: 'browser-agent',
name: 'Browser Agent',
instructions: 'You can browse the web to find information.',
model: 'openai/gpt-5.6-sol',
browser,
})

Constructor parameters
Constructor parameters的直接链接

headless?:

boolean
= true
Whether to run the browser in headless mode (no visible UI).

viewport?:

{ width: number; height: number } | 'window'
= { width: 1280, height: 720 }
Browser viewport dimensions. Controls the size of the browser window. Set to 'window' to match the real browser window instead of a fixed size, supported by the agent-browser provider and by Stagehand when connecting over CDP.

timeout?:

number
Default timeout in milliseconds. Each provider defines its own semantics and default. See the provider reference for details.

cdpUrl?:

string | (() => string | Promise<string>)
CDP WebSocket URL, HTTP endpoint, or sync/async provider function. When provided, connects to an existing browser instead of launching a new one. HTTP endpoints are resolved to WebSocket internally. Can't be used with scope: 'thread' (automatically uses shared scope).

scope?:

'shared' | 'thread'
= 'thread' (or 'shared' when cdpUrl is provided)
Browser instance scope across threads. 'shared' means all threads share a single browser instance. 'thread' means each thread gets its own browser instance (full isolation).

onLaunch?:

(args: { browser: MastraBrowser }) => void | Promise<void>
Callback invoked after the browser reaches 'ready' status.

onClose?:

(args: { browser: MastraBrowser }) => void | Promise<void>
Callback invoked before the browser is closed.

screencast?:

ScreencastOptions
Configuration for streaming browser frames.
ScreencastOptions

format?:

'jpeg' | 'png'
Image format for screencast frames.

quality?:

number
Image quality (1-100). Only applies to JPEG format.

maxWidth?:

number
Maximum width for screencast frames.

maxHeight?:

number
Maximum height for screencast frames.

everyNthFrame?:

number
Capture every Nth frame to reduce bandwidth.

Properties
Properties的直接链接

The following properties (id, name, provider) are abstract and must be defined by concrete provider implementations:

id:

string
Unique identifier for this browser instance. Abstract - defined by provider.

name:

string
Human-readable name of the browser provider (e.g., 'AgentBrowser', 'StagehandBrowser'). Abstract - defined by provider.

provider:

string
Provider identifier (e.g., 'vercel-labs/agent-browser', 'browserbase/stagehand'). Abstract - defined by provider.

headless:

boolean
Whether the browser is running in headless mode.

status:

BrowserStatus
Current browser status: 'pending', 'launching', 'ready', 'error', 'closing', or 'closed'.

Methods
Methods的直接链接

Lifecycle
Lifecycle的直接链接

ensureReady()
ensureready的直接链接

Ensures the browser is launched and ready for use. Automatically called before tool execution. Implemented in the base class.

await browser.ensureReady()

close()
close的直接链接

Closes the browser and cleans up all resources. Implemented in the base class with race-condition-safe handling.

await browser.close()

isBrowserRunning()
isbrowserrunning的直接链接

Checks if the browser is currently running.

const isRunning = browser.isBrowserRunning()

Returns: boolean

Thread management
Thread management的直接链接

setCurrentThread(threadId)
setcurrentthreadthreadid的直接链接

Sets the current thread ID for browser operations. Used internally by the agent runtime.

browser.setCurrentThread('thread-123')

getCurrentThread()
getcurrentthread的直接链接

Gets the current thread ID.

const threadId = browser.getCurrentThread()

Returns: string

hasThreadSession(threadId)
hasthreadsessionthreadid的直接链接

Checks if a thread has an active browser session.

const hasSession = browser.hasThreadSession('thread-123')

Returns: boolean

closeThreadSession(threadId)
closethreadsessionthreadid的直接链接

Closes a specific thread's browser session. With 'thread' scope, it closes that thread's browser instance. With 'shared' scope, it clears the thread state.

await browser.closeThreadSession('thread-123')

Tools
Tools的直接链接

getTools()
gettools的直接链接

Returns the browser tools for use with agents. Each provider returns different tools based on its model.

const tools = browser.getTools()

Returns: Record<string, Tool>

Screencast
Screencast的直接链接

startScreencast(options?)
startscreencastoptions的直接链接

Starts streaming browser frames. Returns a ScreencastStream that emits frame events.

const stream = await browser.startScreencast({ format: 'jpeg', quality: 80 })

stream.on('frame', frame => {
console.log('Frame received:', frame.data.length, 'bytes')
})

stream.on('stop', reason => {
console.log('Screencast stopped:', reason)
})

Returns: Promise<ScreencastStream>

Input injection
Input injection的直接链接

injectMouseEvent(params, threadId?)
injectmouseeventparams-threadid的直接链接

Injects a mouse event into the browser. Used by Studio for live interaction.

await browser.injectMouseEvent({
type: 'mousePressed',
x: 100,
y: 200,
button: 'left',
clickCount: 1,
})

injectKeyboardEvent(params, threadId?)
injectkeyboardeventparams-threadid的直接链接

Injects a keyboard event into the browser. Used by Studio for live interaction.

await browser.injectKeyboardEvent({
type: 'keyDown',
key: 'Enter',
code: 'Enter',
})

State
State的直接链接

getBrowserState(threadId?)
getbrowserstatethreadid的直接链接

Gets the current browser state, including open tabs and the active tab index. Returns null when no state is available.

const state = await browser.getBrowserState('thread-123')
if (state) {
console.log('Active tab:', state.tabs[state.activeTabIndex]?.url)
console.log('Tabs:', state.tabs)
}

Returns: Promise<BrowserState | null>

interface BrowserState {
tabs: BrowserTabState[]
activeTabIndex: number
closeReason?: 'agent' | 'user' | 'process_restart' | 'error'
activeUrlChangeSource?: 'agent' | 'user'
}

interface BrowserTabState {
url: string
title?: string
}

getCurrentUrl(threadId?)
getcurrenturlthreadid的直接链接

Gets the current page URL.

const url = await browser.getCurrentUrl()

Returns: Promise<string | null>

Browser scope
Browser scope的直接链接

The scope option controls how browser instances are shared across conversation threads:

ScopeDescriptionUse case
'shared'All threads share a single browser instanceCost-efficient for non-conflicting tasks
'thread'Each thread gets its own browser instanceFull isolation for concurrent users
// Shared browser for all threads
const sharedBrowser = new AgentBrowser({
scope: 'shared',
})

// Isolated browser per thread
const isolatedBrowser = new AgentBrowser({
scope: 'thread',
})

When using cdpUrl to connect to an external browser, the scope automatically falls back to 'shared' since you can't spawn new browser instances.

Cloud browser providers
Cloud browser providers的直接链接

Connect to cloud browser services using the cdpUrl option:

// Static CDP URL
const browser = new AgentBrowser({
cdpUrl: 'wss://browser.example.com/ws',
})

// Dynamic CDP URL (e.g., session-based)
const browser = new AgentBrowser({
cdpUrl: async () => {
const session = await createBrowserSession()
return session.wsUrl
},
})