Skip to main content
Glama
Xxx00xxX33

Browserbase MCP Server

by Xxx00xxX33

multi_browserbase_stagehand_extract_session

Extract structured data and text from web pages using specific instructions and JSON schema for scraping content or gathering information.

Instructions

Extracts structured information and text content from the current web page based on specific instructions and a defined schema. This tool is ideal for scraping data, gathering information, or pulling specific content from web pages. Use this tool when you need to get text content, data, or information from a page rather than interacting with elements. For interactive elements like buttons, forms, or clickable items, use the observe tool instead. The extraction works best when you provide clear, specific instructions about what to extract and a well-defined JSON schema for the expected output format. This ensures the extracted data is properly structured and usable. (for a specific session)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sessionIdYesThe session ID to use
instructionYesThe specific instruction for what information to extract from the current page. Be as detailed and specific as possible about what you want to extract. For example: 'Extract all product names and prices from the listing page' or 'Get the article title, author, and publication date from this blog post'. The more specific your instruction, the better the extraction results will be. Avoid vague instructions like 'get everything' or 'extract the data'. Instead, be explicit about the exact elements, text, or information you need.

Implementation Reference

  • createMultiSessionAwareTool function: Core handler logic for all multi-session tools including 'multi_browserbase_stagehand_extract_session'. Generates tool schema with prefixed name, adds sessionId to input, retrieves session from store, overrides context methods to use specific session's Stagehand/page/browser, and delegates execution to wrapped original tool.
    function createMultiSessionAwareTool<TInput extends InputType>(
      originalTool: Tool<TInput>,
      options: {
        namePrefix?: string;
        nameSuffix?: string;
      } = {},
    ): Tool<InputType> {
      const { namePrefix = "", nameSuffix = "_session" } = options;
    
      // Create new input schema that includes sessionId
      const originalSchema = originalTool.schema.inputSchema;
      let newInputSchema: z.ZodSchema;
    
      if (originalSchema instanceof z.ZodObject) {
        // If it's a ZodObject, we can spread its shape
        newInputSchema = z.object({
          sessionId: z.string().describe("The session ID to use"),
          ...originalSchema.shape,
        });
      } else {
        // For other schema types, create an intersection
        newInputSchema = z.intersection(
          z.object({ sessionId: z.string().describe("The session ID to use") }),
          originalSchema,
        );
      }
    
      return defineTool({
        capability: originalTool.capability,
        schema: {
          name: `${namePrefix}${originalTool.schema.name}${nameSuffix}`,
          description: `${originalTool.schema.description} (for a specific session)`,
          inputSchema: newInputSchema,
        },
        handle: async (
          context: Context,
          params: z.infer<typeof newInputSchema>,
        ): Promise<ToolResult> => {
          const { sessionId, ...originalParams } = params;
    
          // Get the session
          const session = stagehandStore.get(sessionId);
          if (!session) {
            throw new Error(`Session ${sessionId} not found`);
          }
    
          // Create a temporary context that points to the specific session
          const sessionContext = Object.create(context);
          sessionContext.currentSessionId =
            session.metadata?.bbSessionId || sessionId;
          sessionContext.getStagehand = async () => session.stagehand;
          sessionContext.getActivePage = async () => session.page;
          sessionContext.getActiveBrowser = async () => session.browser;
    
          // Call the original tool's handler with the session-specific context
          return originalTool.handle(sessionContext, originalParams);
        },
      });
    }
  • Specific registration/definition of extractWithSessionTool, which names it 'multi_browserbase_stagehand_extract_session' (multi_ + browserbase_stagehand_extract + _session).
    export const extractWithSessionTool = createMultiSessionAwareTool(extractTool, {
      namePrefix: "multi_",
      nameSuffix: "_session",
    });
  • Inner handler of the original extractTool (browserbase_stagehand_extract), which performs the page.extract() call using Stagehand and returns the structured extraction result. Delegated to by the multi-session wrapper.
    async function handleExtract(
      context: Context,
      params: ExtractInput,
    ): Promise<ToolResult> {
      const action = async (): Promise<ToolActionResult> => {
        try {
          const stagehand = await context.getStagehand();
    
          const extraction = await stagehand.page.extract(params.instruction);
    
          return {
            content: [
              {
                type: "text",
                text: `Extracted content:\n${JSON.stringify(extraction, null, 2)}`,
              },
            ],
          };
        } catch (error) {
          const errorMsg = error instanceof Error ? error.message : String(error);
          throw new Error(`Failed to extract content: ${errorMsg}`);
        }
      };
    
      return {
        action,
        waitForNetwork: false,
      };
    }
  • Registration: Includes extractWithSessionTool in the multiSessionTools array, which is merged into the main TOOLS export used by the MCP server.
    export const multiSessionTools = [
      createSessionTool,
      listSessionsTool,
      closeSessionTool,
      navigateWithSessionTool,
      actWithSessionTool,
      extractWithSessionTool,
      observeWithSessionTool,
    ];
  • Original schema definition for browserbase_stagehand_extract tool, which is extended by adding 'sessionId' parameter for the multi-session version.
    const extractSchema: ToolSchema<typeof ExtractInputSchema> = {
      name: "browserbase_stagehand_extract",
      description:
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It discloses that extraction works best with clear instructions and a well-defined schema, adding useful context about performance and prerequisites. However, it lacks details on error handling, rate limits, or authentication needs, leaving gaps in behavioral transparency for a tool with no annotation support.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized and front-loaded, with the core purpose stated first. Every sentence adds value, such as usage guidelines and performance tips, but it could be slightly more concise by avoiding minor redundancy (e.g., repeating 'specific' and 'extract'). Overall, it's efficient with zero waste.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (extraction with instructions and schema) and lack of annotations or output schema, the description does well by covering purpose, usage, and behavioral tips. However, it could improve by mentioning output format or error cases, as there's no output schema to rely on. It's mostly complete but has minor gaps.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents both parameters thoroughly. The description adds minimal value beyond the schema by emphasizing the importance of specific instructions, but it doesn't provide additional syntax or format details. This meets the baseline of 3 when schema coverage is high.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with specific verbs ('extracts structured information and text content') and resources ('from the current web page'), distinguishing it from sibling tools like 'observe' for interactive elements. It explicitly mentions extraction based on instructions and schema, making the function unambiguous.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit guidance on when to use this tool ('when you need to get text content, data, or information from a page') and when not to ('for interactive elements like buttons, forms, or clickable items, use the observe tool instead'). It also offers alternatives by naming the 'observe' tool, ensuring clear differentiation from siblings.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Xxx00xxX33/mcp-server-browserbase'

If you have feedback or need assistance with the MCP directory API, please join our Discord server