Skip to main content
Glama
RonsDad
by RonsDad

browserbase_session_close

Properly terminate a Browserbase automation session to clean up browser resources and stop session recording.

Instructions

Closes the current Browserbase session by properly shutting down the Stagehand instance, which handles browser cleanup and terminates the session recording.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • Handler function that closes the current Browserbase session. It retrieves the session using getSession, closes the Stagehand instance if available, cleans up the session, resets the context's current session ID to default, and returns appropriate success or info messages. Includes error handling.
    async function handleCloseSession(context: Context): Promise<ToolResult> {
      const action = async (): Promise<ToolActionResult> => {
        // Store the current session ID before it's potentially changed.
        const previousSessionId = context.currentSessionId;
        let stagehandClosedSuccessfully = false;
        let stagehandCloseErrorMessage = "";
    
        // Step 1: Attempt to get the session and close Stagehand
        let browserbaseSessionId: string | undefined;
        try {
          const session = await getSession(
            previousSessionId,
            context.config,
            false,
          );
    
          if (session && session.stagehand) {
            // Store the actual Browserbase session ID for the replay URL
            browserbaseSessionId = session.sessionId;
    
            process.stderr.write(
              `[tool.closeSession] Attempting to close Stagehand for session: ${previousSessionId || "default"} (Browserbase ID: ${browserbaseSessionId})`,
            );
    
            // Use Stagehand's close method which handles browser cleanup properly
            await session.stagehand.close();
            stagehandClosedSuccessfully = true;
    
            process.stderr.write(
              `[tool.closeSession] Stagehand and browser connection for session (${previousSessionId}) closed successfully.`,
            );
    
            // Clean up the session from tracking
            await cleanupSession(previousSessionId);
    
            if (browserbaseSessionId) {
              process.stderr.write(
                `[tool.closeSession] View session replay at https://www.browserbase.com/sessions/${browserbaseSessionId}`,
              );
            }
          } else {
            process.stderr.write(
              `[tool.closeSession] No Stagehand instance found for session: ${previousSessionId || "default/unknown"}`,
            );
          }
        } catch (error: unknown) {
          stagehandCloseErrorMessage =
            error instanceof Error ? error.message : String(error);
          process.stderr.write(
            `[tool.closeSession] Error retrieving or closing Stagehand (session ID was ${previousSessionId || "default/unknown"}): ${stagehandCloseErrorMessage}`,
          );
        }
    
        // Step 2: Always reset the context's current session ID to default
        const oldContextSessionId = context.currentSessionId;
        context.currentSessionId = defaultSessionId;
        process.stderr.write(
          `[tool.closeSession] Session context reset to default. Previous context session ID was ${oldContextSessionId || "default/unknown"}.`,
        );
    
        // Step 3: Determine the result message
        if (stagehandCloseErrorMessage && !stagehandClosedSuccessfully) {
          throw new Error(
            `Failed to close the Stagehand session (session ID in context was ${previousSessionId || "default/unknown"}). Error: ${stagehandCloseErrorMessage}. Session context has been reset to default.`,
          );
        }
    
        if (stagehandClosedSuccessfully) {
          let successMessage = `Browserbase session (${previousSessionId || "default"}) closed successfully via Stagehand. Context reset to default.`;
          if (browserbaseSessionId && previousSessionId !== defaultSessionId) {
            successMessage += ` View replay at https://www.browserbase.com/sessions/${browserbaseSessionId}`;
          }
          return { content: [{ type: "text", text: successMessage }] };
        }
    
        // No Stagehand instance was found
        let infoMessage =
          "No active Stagehand session found to close. Session context has been reset to default.";
        if (previousSessionId && previousSessionId !== defaultSessionId) {
          infoMessage = `No active Stagehand session found for session ID '${previousSessionId}'. The context has been reset to default.`;
        }
        return { content: [{ type: "text", text: infoMessage }] };
      };
    
      return {
        action: action,
        waitForNetwork: false,
      };
    }
  • Zod input schema (empty object, no parameters required) and tool schema definition including name, description, and input schema reference.
    const CloseSessionInputSchema = z.object({});
    
    const closeSessionSchema: ToolSchema<typeof CloseSessionInputSchema> = {
      name: "browserbase_session_close",
      description:
        "Closes the current Browserbase session by properly shutting down the Stagehand instance, which handles browser cleanup and terminates the session recording.",
      inputSchema: CloseSessionInputSchema,
    };
  • Tool object registration combining the schema and handler function. Exported as part of the default export array for inclusion in the MCP tools registry.
    const closeSessionTool: Tool<typeof CloseSessionInputSchema> = {
      capability: "core",
      schema: closeSessionSchema,
      handle: handleCloseSession,
    };
    
    export default [createSessionTool, closeSessionTool];
Behavior3/5

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

With no annotations provided, the description carries the full burden. It discloses key behavioral traits: it performs cleanup ('browser cleanup') and termination ('terminates the session recording'), indicating a destructive operation. However, it lacks details on side effects (e.g., what happens to open tabs), error handling, or prerequisites (e.g., must have an active session). No contradiction with annotations exists.

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 a single, well-structured sentence that efficiently conveys the tool's purpose, mechanism, and outcomes without redundancy. It is front-loaded with the core action ('Closes the current Browserbase session') and adds only essential details, making every word earn its place.

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 (a session-closing operation with no parameters and no output schema), the description is mostly complete. It explains what the tool does and its effects, but lacks information on return values or error cases. With no annotations, it could benefit from more behavioral context, but it adequately covers the basics for a simple tool.

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 0 parameters with 100% coverage, so no parameter documentation is needed. The description does not mention any parameters, which is appropriate. A baseline of 4 is applied for 0 parameters, as it adds no unnecessary information and aligns with the schema.

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 specific action ('Closes') and resource ('current Browserbase session'), distinguishing it from siblings like 'browserbase_session_create' (which opens sessions) and 'browserbase_stagehand_*' tools (which operate within sessions). It also specifies the mechanism ('properly shutting down the Stagehand instance') and outcomes ('browser cleanup and terminates the session recording').

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

Usage Guidelines4/5

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

The description implies usage context by mentioning 'current Browserbase session' and 'Stagehand instance,' suggesting it should be used after session activities. However, it does not explicitly state when to use it versus alternatives (e.g., no guidance on whether it's mandatory after other tools or if sessions auto-close). The sibling tools include session management and multi-session variants, but no direct comparisons are provided.

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