Skip to main content
Glama
RonsDad
by RonsDad

browserbase_session_create

Create a cloud browser session for web automation tasks using Browserbase and Stagehand, enabling data extraction and page interaction through AI commands.

Instructions

Create or reuse a single cloud browser session using Browserbase with fully initialized Stagehand. WARNING: This tool is for SINGLE browser workflows only. If you need multiple browser sessions running simultaneously (parallel scraping, A/B testing, multiple accounts), use 'multi_browserbase_stagehand_session_create' instead. This creates one browser session with all configuration flags (proxies, stealth, viewport, cookies, etc.) and initializes Stagehand to work with that session. Updates the active session.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sessionIdNoOptional session ID to use/reuse. If not provided or invalid, a new session is created.

Implementation Reference

  • The handler function for the 'browserbase_session_create' tool. It determines the target session ID, uses SessionManager to create or ensure the session (calling ensureDefaultSessionInternal or createNewBrowserSession), validates the session, sets the context's current session, fetches the debugger URL, logs details, and returns content with session and debugger URLs.
    async function handleCreateSession(
      context: Context,
      params: CreateSessionInput,
    ): Promise<ToolResult> {
      const action = async (): Promise<ToolActionResult> => {
        try {
          const config = context.config; // Get config from context
          let targetSessionId: string;
    
          if (params.sessionId) {
            const projectId = config.browserbaseProjectId || "";
            targetSessionId = `${params.sessionId}_${projectId}`;
            process.stderr.write(
              `[tool.createSession] Attempting to create/assign session with specified ID: ${targetSessionId}`,
            );
          } else {
            targetSessionId = defaultSessionId;
          }
    
          let session: BrowserSession;
          if (targetSessionId === defaultSessionId) {
            session = await ensureDefaultSessionInternal(config);
          } else {
            // When user provides a sessionId, we want to resume that Browserbase session
            session = await createNewBrowserSession(
              targetSessionId,
              config,
              params.sessionId,
            );
          }
    
          if (
            !session ||
            !session.browser ||
            !session.page ||
            !session.sessionId ||
            !session.stagehand
          ) {
            throw new Error(
              `SessionManager failed to return a valid session object with actualSessionId for ID: ${targetSessionId}`,
            );
          }
    
          context.currentSessionId = targetSessionId;
          const bb = new Browserbase({
            apiKey: config.browserbaseApiKey,
          });
          const debugUrl = (await bb.sessions.debug(session.sessionId))
            .debuggerFullscreenUrl;
          process.stderr.write(
            `[tool.connected] Successfully connected to Browserbase session. Internal ID: ${targetSessionId}, Actual ID: ${session.sessionId}`,
          );
    
          process.stderr.write(
            `[SessionManager] Browserbase Live Session View URL: https://www.browserbase.com/sessions/${session.sessionId}`,
          );
    
          process.stderr.write(
            `[SessionManager] Browserbase Live Debugger URL: ${debugUrl}`,
          );
    
          return {
            content: [
              {
                type: "text",
                text: `Browserbase Live Session View URL: https://www.browserbase.com/sessions/${session.sessionId}\nBrowserbase Live Debugger URL: ${debugUrl}`,
              },
            ],
          };
        } catch (error: unknown) {
          const errorMessage =
            error instanceof Error ? error.message : String(error);
          process.stderr.write(
            `[tool.createSession] Action failed: ${errorMessage}`,
          );
          // Re-throw to be caught by Context.run's error handling for actions
          throw new Error(`Failed to create Browserbase session: ${errorMessage}`);
        }
      };
    
      // Return the ToolResult structure expected by Context.run
      return {
        action: action,
        waitForNetwork: false,
      };
    }
  • Zod input schema and tool schema definition for the 'browserbase_session_create' tool, including the optional sessionId parameter.
    const CreateSessionInputSchema = z.object({
      // Keep sessionId optional, but clarify its role
      sessionId: z
        .string()
        .optional()
        .describe(
          "Optional session ID to use/reuse. If not provided or invalid, a new session is created.",
        ),
    });
    type CreateSessionInput = z.infer<typeof CreateSessionInputSchema>;
    
    const createSessionSchema: ToolSchema<typeof CreateSessionInputSchema> = {
      name: "browserbase_session_create",
      description:
        "Create or reuse a single cloud browser session using Browserbase with fully initialized Stagehand. WARNING: This tool is for SINGLE browser workflows only. If you need multiple browser sessions running simultaneously (parallel scraping, A/B testing, multiple accounts), use 'multi_browserbase_stagehand_session_create' instead. This creates one browser session with all configuration flags (proxies, stealth, viewport, cookies, etc.) and initializes Stagehand to work with that session. Updates the active session.",
      inputSchema: CreateSessionInputSchema,
    };
  • The tools index file collects all tools including sessionTools (which contains browserbase_session_create) into the TOOLS array exported for registration in the MCP server.
    // Export all tools as array
    export const TOOLS = [
      ...multiSessionTools,
      ...sessionTools,
      navigateTool,
      actTool,
      extractTool,
      observeTool,
      screenshotTool,
      getUrlTool,
    ];
  • src/index.ts:196-226 (registration)
    The MCP server registration loop that registers all tools from TOOLS, including 'browserbase_session_create', by calling server.tool with name, description, schema, and a wrapper handler that invokes context.run on the tool.
    const tools: MCPToolsArray = [...TOOLS];
    
    // Register each tool with the Smithery server
    tools.forEach((tool) => {
      if (tool.schema.inputSchema instanceof z.ZodObject) {
        server.tool(
          tool.schema.name,
          tool.schema.description,
          tool.schema.inputSchema.shape,
          async (params: z.infer<typeof tool.schema.inputSchema>) => {
            try {
              const result = await context.run(tool, params);
              return result;
            } catch (error) {
              const errorMessage =
                error instanceof Error ? error.message : String(error);
              process.stderr.write(
                `[Smithery Error] ${new Date().toISOString()} Error running tool ${tool.schema.name}: ${errorMessage}\n`,
              );
              throw new Error(
                `Failed to run tool '${tool.schema.name}': ${errorMessage}`,
              );
            }
          },
        );
      } else {
        console.warn(
          `Tool "${tool.schema.name}" has an input schema that is not a ZodObject. Schema type: ${tool.schema.inputSchema.constructor.name}`,
        );
      }
    });
  • Key helper function called by the handler to create a new or resume Browserbase session using Stagehand, which is central to the tool's logic.
    export async function createNewBrowserSession(
      newSessionId: string,
      config: Config,
      resumeSessionId?: string,
    ): Promise<BrowserSession> {
      if (!config.browserbaseApiKey) {
        throw new Error("Browserbase API Key is missing in the configuration.");
      }
      if (!config.browserbaseProjectId) {
        throw new Error("Browserbase Project ID is missing in the configuration.");
      }
    
      try {
        process.stderr.write(
          `[SessionManager] ${resumeSessionId ? "Resuming" : "Creating"} Stagehand session ${newSessionId}...\n`,
        );
    
        // Create and initialize Stagehand instance using shared function
        const stagehand = await createStagehandInstance(
          config,
          {
            ...(resumeSessionId && { browserbaseSessionID: resumeSessionId }),
          },
          newSessionId,
        );
    
        // Get the page and browser from Stagehand
        const page = stagehand.page as unknown as Page;
        const browser = page.context().browser();
    
        if (!browser) {
          throw new Error("Failed to get browser from Stagehand page context");
        }
    
        const browserbaseSessionId = stagehand.browserbaseSessionID;
    
        process.stderr.write(
          `[SessionManager] Stagehand initialized with Browserbase session: ${browserbaseSessionId}\n`,
        );
        process.stderr.write(
          `[SessionManager] Browserbase Live Debugger URL: https://www.browserbase.com/sessions/${browserbaseSessionId}\n`,
        );
    
        // Set up disconnect handler
        browser.on("disconnected", () => {
          process.stderr.write(`[SessionManager] Disconnected: ${newSessionId}\n`);
          browsers.delete(newSessionId);
          if (defaultBrowserSession && defaultBrowserSession.browser === browser) {
            process.stderr.write(
              `[SessionManager] Disconnected (default): ${newSessionId}\n`,
            );
            defaultBrowserSession = null;
          }
          if (
            activeSessionId === newSessionId &&
            newSessionId !== defaultSessionId
          ) {
            process.stderr.write(
              `[SessionManager] WARN - Active session disconnected, resetting to default: ${newSessionId}\n`,
            );
            setActiveSessionId(defaultSessionId);
          }
        });
    
        // Add cookies to the context if they are provided in the config
        if (
          config.cookies &&
          Array.isArray(config.cookies) &&
          config.cookies.length > 0
        ) {
          await addCookiesToContext(
            page.context() as BrowserContext,
            config.cookies,
          );
        }
    
        const sessionObj: BrowserSession = {
          browser,
          page,
          sessionId: browserbaseSessionId!,
          stagehand,
        };
    
        browsers.set(newSessionId, sessionObj);
    
        if (newSessionId === defaultSessionId) {
          defaultBrowserSession = sessionObj;
        }
    
        setActiveSessionId(newSessionId);
        process.stderr.write(
          `[SessionManager] Session created and active: ${newSessionId}\n`,
        );
    
        return sessionObj;
      } catch (creationError) {
        const errorMessage =
          creationError instanceof Error
            ? creationError.message
            : String(creationError);
        process.stderr.write(
          `[SessionManager] Creating session ${newSessionId} failed: ${errorMessage}\n`,
        );
        throw new Error(
          `Failed to create/connect session ${newSessionId}: ${errorMessage}`,
        );
      }
    }
Behavior4/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It effectively describes key behaviors: it creates or reuses a session based on sessionId, initializes Stagehand, updates the active session, and includes configuration flags (proxies, stealth, viewport, cookies). However, it lacks details on error handling, rate limits, or authentication needs, which are important for a creation tool.

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

Conciseness5/5

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

The description is front-loaded with the core purpose, followed by a WARNING for usage guidelines, and additional details about configuration and updates. Every sentence adds necessary information without redundancy, making it efficient and well-structured.

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 no annotations, no output schema, and a simple input schema, the description is mostly complete. It covers purpose, usage, parameters, and key behaviors. However, as a session creation tool, it could benefit from mentioning potential errors or return values, slightly reducing completeness.

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

Parameters4/5

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

The input schema has 100% description coverage, so the baseline is 3. The description adds value by explaining the parameter's effect: 'Optional session ID to use/reuse. If not provided or invalid, a new session is created.' This clarifies the semantics beyond the schema's technical definition, justifying a higher score.

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: 'Create or reuse a single cloud browser session using Browserbase with fully initialized Stagehand.' It specifies the verb ('create or reuse'), resource ('cloud browser session'), and distinguishes it from its sibling 'multi_browserbase_stagehand_session_create' by emphasizing 'SINGLE browser workflows only.' This provides specific differentiation.

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 explicitly states when to use this tool ('for SINGLE browser workflows only') and when not to use it ('If you need multiple browser sessions running simultaneously... use 'multi_browserbase_stagehand_session_create' instead'). It provides clear alternatives and exclusions, making it easy for an agent to choose correctly.

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/RonsDad/mcp-server-browserbase'

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