Overview
Stagehand supports integration with Model Context Protocol (MCP) servers, allowing your agents to access external tools and services like Notion, databases, and other APIs.
You must enable experimental: true in your Stagehand configuration to use MCP integrations.
MCP Integration via URL
The simplest way to integrate an MCP server is by providing its URL:
import { Stagehand } from "@stagehand/core";
async function example(stagehand: Stagehand) {
const page = stagehand.context.pages()[0];
await page.goto("https://www.google.com");
const agent = stagehand.agent({
integrations: [
`https://mcp.exa.ai/mcp?exaApiKey=${process.env.EXA_API_KEY}`,
],
systemPrompt: `You are a helpful assistant that can use a browser as well as external tools such as web search.
You have access to the Exa search tool to find information on the web.
When looking for products to buy, make sure to search for current and reliable information.
Be thorough in your research before making purchase decisions.`,
});
const result = await agent.execute(
"Use one of the tools from Exa to search for the top headphones of 2025. After doing so, use the browser and go through the checkout flow for the best one.",
);
console.log(result);
}
(async () => {
const stagehand = new Stagehand({
env: "LOCAL",
model: "openai/gpt-4.1",
verbose: 1,
logInferenceToFile: true,
experimental: true,
});
try {
await stagehand.init();
await example(stagehand);
} catch (error) {
console.error("Error running example:", error);
} finally {
await stagehand.close();
}
})();
MCP Integration via Connection
The advanced connection API shown below is currently commented out in the examples. Check the Stagehand documentation for the latest MCP connection methods.
For more control, you can connect to MCP servers programmatically:
import { Stagehand } from "@stagehand/core";
import { connectToMCPServer } from "@stagehand/core/mcp";
import chalk from "chalk";
async function main() {
console.log(`\n${chalk.bold("Stagehand 🤘 MCP Demo")}\n`);
// Initialize Stagehand
const stagehand = new Stagehand({
env: "LOCAL",
experimental: true,
});
await stagehand.init();
// Connect to Notion MCP server
const notionClient = await connectToMCPServer({
command: "npx",
args: ["-y", "@notionhq/notion-mcp-server"],
env: {
NOTION_TOKEN: process.env.NOTION_TOKEN,
},
});
try {
const page = stagehand.context.pages()[0];
// Create agent with MCP integration
const agent = stagehand.agent({
provider: "anthropic",
model: "claude-sonnet-4-20250514",
instructions: `You are a helpful assistant that can use a web browser.
You are currently on the following page: ${page.url()}.
Do not ask follow up questions, the user will trust your judgement.
You have access to the Notion MCP.`,
options: {
apiKey: process.env.ANTHROPIC_API_KEY,
},
integrations: [notionClient],
});
await page.goto("https://www.google.com");
const instruction =
"Check the Agent Tasks page in notion, read your tasks, perform them and update the notion page with the results.";
console.log(`Instruction: ${chalk.white(instruction)}`);
const result = await agent.execute({
instruction,
maxSteps: 50,
});
console.log(`${chalk.green("✓")} Execution complete`);
console.log(`${chalk.yellow("⤷")} Result:`);
console.log(chalk.white(JSON.stringify(result, null, 2)));
} catch (error) {
console.log(`${chalk.red("✗")} Error: ${error}`);
if (error instanceof Error && error.stack) {
console.log(chalk.dim(error.stack.split("\n").slice(1).join("\n")));
}
} finally {
await stagehand.close();
}
}
main().catch((error) => {
console.log(`${chalk.red("✗")} Unhandled error in main function`);
console.log(chalk.red(error));
});
Available MCP Servers
Exa Search
Provides web search capabilities:
integrations: [
`https://mcp.exa.ai/mcp?exaApiKey=${process.env.EXA_API_KEY}`,
]
Notion
Access and modify Notion pages:
const notionClient = await connectToMCPServer({
command: "npx",
args: ["-y", "@notionhq/notion-mcp-server"],
env: {
NOTION_TOKEN: process.env.NOTION_TOKEN,
},
});
integrations: [notionClient]
Custom MCP Servers
You can create and integrate your own MCP servers:
const customClient = await connectToMCPServer({
command: "node",
args: ["path/to/your/mcp-server.js"],
env: {
API_KEY: process.env.YOUR_API_KEY,
},
});
integrations: [customClient]
Configuration
Enable Experimental Mode
MCP integrations require experimental mode:
const stagehand = new Stagehand({
experimental: true, // Required for MCP
});
System Prompts
Tell the agent about available MCP tools:
systemPrompt: `You are a helpful assistant that can use a browser as well as external tools.
You have access to the Exa search tool to find information on the web.
You have access to Notion to read and update pages.
Be thorough in your research before making decisions.`
Multiple Integrations
You can provide multiple MCP servers:
const agent = stagehand.agent({
integrations: [
`https://mcp.exa.ai/mcp?exaApiKey=${process.env.EXA_API_KEY}`,
notionClient,
customClient,
],
});
Use Cases
Research and Documentation
const agent = stagehand.agent({
integrations: [
`https://mcp.exa.ai/mcp?exaApiKey=${process.env.EXA_API_KEY}`,
notionClient,
],
systemPrompt: `Research topics using Exa search and document findings in Notion.`,
});
const result = await agent.execute(
"Research the latest trends in AI automation and create a summary page in Notion."
);
Data Collection and Storage
const agent = stagehand.agent({
integrations: [databaseClient],
systemPrompt: `Extract data from websites and store in the database.`,
});
const result = await agent.execute(
"Visit the top 10 e-commerce sites, extract product categories, and store in the database."
);
Task Automation
const agent = stagehand.agent({
integrations: [notionClient, slackClient],
systemPrompt: `Check Notion for tasks, complete them, and notify via Slack.`,
});
const result = await agent.execute(
"Check the Agent Tasks page in Notion, complete all pending tasks, and send a summary to #automation channel in Slack."
);
Key Concepts
MCP Server Connection
MCP servers can be connected via:
- URL: Direct HTTP/HTTPS endpoints
- Command: Running local MCP server processes
Environment Variables
Pass API keys and credentials through the env parameter:
env: {
NOTION_TOKEN: process.env.NOTION_TOKEN,
API_KEY: process.env.API_KEY,
}
Agent Instructions
Clearly communicate available MCP tools in system prompts so the agent knows when to use them.
Best Practices
- Enable experimental mode - Required for MCP integrations
- Document available tools - Tell the agent about MCP capabilities in system prompts
- Secure credentials - Use environment variables for API keys
- Handle errors - MCP servers can fail; implement proper error handling
- Limit steps - Set reasonable
maxSteps to prevent runaway execution
- Test integrations - Verify MCP servers work before complex workflows
Troubleshooting
MCP Server Not Found
Ensure the MCP server package is installed:
npm install -g @notionhq/notion-mcp-server
Authentication Errors
Verify environment variables are set:
export NOTION_TOKEN="your_token_here"
export EXA_API_KEY="your_key_here"
Connection Timeouts
Increase timeout or check MCP server availability:
const client = await connectToMCPServer({
command: "npx",
args: ["-y", "@notionhq/notion-mcp-server"],
env: { NOTION_TOKEN: process.env.NOTION_TOKEN },
timeout: 30000, // 30 seconds
});
Next Steps