Skip to main content
Glama

browserbase_session_close

Properly shuts down browser sessions by terminating the Stagehand instance to handle cleanup and stop recordings.

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

  • The handleCloseSession function that implements the tool's core logic: gets the current session, closes the Stagehand instance if available, cleans up the session tracking, resets the context's current session ID to default, and returns appropriate success or info messages with 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,
      };
    }
  • Defines the input schema (empty, no params needed) and the tool schema including the unique name 'browserbase_session_close', description, and inputSchema 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,
    };
  • Registers the tool by creating the closeSessionTool object that combines the schema and handler function, and exports it within the array of session tools.
    const closeSessionTool: Tool<typeof CloseSessionInputSchema> = {
      capability: "core",
      schema: closeSessionSchema,
      handle: handleCloseSession,
    };
    
    export default [createSessionTool, closeSessionTool];
  • Aggregates all tools, including sessionTools (which contains browserbase_session_close), into the central TOOLS array exported for use in MCP server setup.
    export const TOOLS = [
      ...multiSessionTools,
      ...sessionTools,
      navigateTool,
      actTool,
      extractTool,
      observeTool,
      screenshotTool,
      getUrlTool,
    ];
  • src/index.ts:192-222 (registration)
    Final MCP server registration: loops over TOOLS array and calls server.tool() for each, using the tool's schema.name ('browserbase_session_close'), description, input schema shape, and a wrapper handler that invokes context.run(tool, params).
    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}`,
        );
      }
    });
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 a shutdown operation ('closes', 'shutting down'), handles cleanup ('browser cleanup'), and terminates recording ('terminates the session recording'), which are useful for understanding effects. However, it lacks details on error handling, side effects, or confirmation of success.

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 action, target, and key outcomes ('shutting down', 'cleanup', 'terminates recording') without any redundant information. It's front-loaded with the main purpose.

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

Completeness3/5

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

Given no annotations and no output schema, the description provides basic operational context but is incomplete. It explains what the tool does but lacks information on return values, error conditions, or dependencies (e.g., must have an active session). For a session management tool, more details on behavioral implications would be helpful.

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?

There are 0 parameters, and schema description coverage is 100%, so the baseline is high. The description doesn't need to add parameter details, and it correctly implies no inputs are required for this operation, which is appropriate for a zero-parameter tool.

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

Purpose4/5

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

The description clearly states the verb ('Closes') and resource ('current Browserbase session'), and mentions the mechanism ('properly shutting down the Stagehand instance'). It distinguishes from siblings like 'browserbase_session_create' by indicating termination rather than creation, though it doesn't explicitly contrast with all session-related tools.

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

Usage Guidelines2/5

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

The description implies usage after a session is active but provides no explicit guidance on when to use this tool versus alternatives (e.g., when to close vs. keep a session open) or any prerequisites. It mentions 'current Browserbase session' but doesn't specify how to identify or handle multiple sessions.

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

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