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}`);
}
},
});