Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 60 additions & 2 deletions packages/docs/v4/integrations/mastra.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,75 @@ description: "Give a Mastra agent persistent Stagehand browser tools over MCP/st
The Mastra integration connects an agent to the Stagehand facade MCP server over MCP/stdio. The MCP client remains open for the agent run, so browser state survives across tool calls.

<Note>
Stagehand ships this experimental integration from the repository rather than publishing it as a standalone adapter.
The source example is maintained in the Stagehand repository. For an existing application, prefer the host’s MCP client and the Stagehand facade MCP server described below.
</Note>

## Add Stagehand to an existing agent

Use Mastra’s supported tool integration: `MCPClient` from `@mastra/mcp`. This is an [official SDK/MCP extension point](https://mastra.ai/docs/agents/tools); you do not need a separate host marketplace plugin.

<Note>
The portable setup below requires the first `@browserbasehq/stagehand-mcp@0.1.0` release. Until that release is published, use the source example further down this page. Node.js 24+ is required to run the MCP server.
</Note>

Install the host libraries in your application:

```bash
pnpm add @mastra/core @mastra/mcp
```

Configure your agent’s model credentials as usual. The browser uses local Chrome unless you export `BROWSERBASE_API_KEY`. The Mastra host forwards the `STAGEHAND_*` and `BROWSERBASE_*` variables to the MCP child, including any separate Stagehand model configuration. Your agent’s model-provider credential stays in the host.

```typescript
import { MCPClient } from "@mastra/mcp";
import { Agent } from "@mastra/core/agent";

const env = Object.fromEntries(
Object.entries(process.env).filter(
(entry): entry is [string, string] =>
(entry[0].startsWith("STAGEHAND_") || entry[0].startsWith("BROWSERBASE_")) &&
entry[1] !== undefined,
),
);
const client = new MCPClient({
id: "stagehand-browser",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: When an application creates multiple clients in one process, this fixed ID lets @mastra/mcp reuse or disconnect another client, terminating its MCP/browser session. Generate a unique ID for each client or explicitly share one singleton client.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/docs/v4/integrations/mastra.mdx, line 40:

<comment>When an application creates multiple clients in one process, this fixed ID lets `@mastra/mcp` reuse or disconnect another client, terminating its MCP/browser session. Generate a unique ID for each client or explicitly share one singleton client.</comment>

<file context>
@@ -6,17 +6,75 @@ description: "Give a Mastra agent persistent Stagehand browser tools over MCP/st
+  ),
+);
+const client = new MCPClient({
+  id: "stagehand-browser",
+  servers: {
+    stagehand: {
</file context>

servers: {
stagehand: {
command: "npx",
args: ["-y", "@browserbasehq/stagehand-mcp@0.1.0"],
env,
},
},
});

try {
const tools = await client.listTools();
const agent = new Agent({
id: "browser-agent",
name: "Browser agent",
instructions: "Use the Stagehand tools to browse. Take a snapshot before interacting with page elements.",
model: "openai/gpt-5.6-luna",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: With the documented OpenAI credential, this model string routes through Mastra’s gateway instead of the OpenAI provider. Import openai from @ai-sdk/openai and install it, or document the required gateway credential.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/docs/v4/integrations/mastra.mdx, line 56:

<comment>With the documented OpenAI credential, this model string routes through Mastra’s gateway instead of the OpenAI provider. Import `openai` from `@ai-sdk/openai` and install it, or document the required gateway credential.</comment>

<file context>
@@ -6,17 +6,75 @@ description: "Give a Mastra agent persistent Stagehand browser tools over MCP/st
+    id: "browser-agent",
+    name: "Browser agent",
+    instructions: "Use the Stagehand tools to browse. Take a snapshot before interacting with page elements.",
+    model: "openai/gpt-5.6-luna",
+    tools,
+  });
</file context>

tools,
});
const result = await agent.generate("Open https://example.com and report its title.", {
maxSteps: 20,
});
console.log(result.text);
} finally {
await client.disconnect();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: When discovery or agent generation fails and disconnect() also rejects, this finally replaces the primary error with the cleanup failure. Catch and report disconnect errors while preserving the original failure.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/docs/v4/integrations/mastra.mdx, line 64:

<comment>When discovery or agent generation fails and `disconnect()` also rejects, this `finally` replaces the primary error with the cleanup failure. Catch and report disconnect errors while preserving the original failure.</comment>

<file context>
@@ -6,17 +6,75 @@ description: "Give a Mastra agent persistent Stagehand browser tools over MCP/st
+  });
+  console.log(result.text);
+} finally {
+  await client.disconnect();
+}
+```
</file context>
Suggested change
await client.disconnect();
await client.disconnect().catch((disconnectError) => {
console.error(
`Warning: failed to disconnect MCP client: ${disconnectError instanceof Error ? disconnectError.message : String(disconnectError)}`,
);
});

}
```

Keep the connection open until the entire agent run finishes. Closing it releases the server and its browser.

## Prerequisites

- Node.js 24 or newer
- pnpm 11.10.0
- An OpenAI API key for the example agent
- A current Google Chrome installation for local browser mode

## Quickstart
## Run the source example

<Steps>
<Step title="Clone and build Stagehand">
Expand Down
4 changes: 4 additions & 0 deletions packages/integrations/mastra/README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Mastra + Stagehand facade over MCP/stdio

## Supported integration route

Use `MCPClient` from `@mastra/mcp`, as described in the [official Mastra documentation](https://mastra.ai/docs/agents/tools). You do not need a separate host marketplace plugin. The [Stagehand guide](https://docs.stagehand.dev/v4/integrations/mastra#add-stagehand-to-an-existing-agent) includes a portable setup using the Stagehand facade MCP server (`@browserbasehq/stagehand-mcp`), pending its first 0.1.0 release. The source example below remains available before publication.

This example connects Mastra to the Stagehand facade MCP server over stdio. It
exposes the facade's `run`, `snapshot`, and `screenshot` tools to a Mastra agent,
using agent instructions imported from the integrations package.
Expand Down
Loading