Skip to main content
Glama

browserbase_session_close

Close the current cloud browser session and reset the active context to free up resources and prepare for new browsing tasks.

Instructions

Close the current Browserbase session and reset the active context.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The handler function that performs the session close operation: retrieves current session, cleans up via SessionManager, handles errors, resets context to default, and returns appropriate text content with replay URL if available.
    async function handleCloseSession(context: Context): Promise<ToolResult> {
      const action = async (): Promise<ToolActionResult> => {
        // Store the current session ID before cleanup
        const previousSessionId = context.currentSessionId;
        let cleanupSuccessful = false;
        let cleanupErrorMessage = "";
    
        // Step 1: Get session info before cleanup
        let browserbaseSessionId: string | undefined;
        const sessionManager = context.getSessionManager();
    
        try {
          const session = await sessionManager.getSession(
            previousSessionId,
            context.config,
            false,
          );
    
          if (session && session.stagehand) {
            // Store the actual Browserbase session ID for the replay URL
            browserbaseSessionId = session.sessionId;
    
            // cleanupSession handles both closing Stagehand and cleanup (idempotent)
            await sessionManager.cleanupSession(previousSessionId);
            cleanupSuccessful = true;
          } else {
            process.stderr.write(
              `[tool.closeSession] No session found for ID: ${previousSessionId || "default/unknown"}\n`,
            );
          }
        } catch (error: unknown) {
          cleanupErrorMessage =
            error instanceof Error ? error.message : String(error);
          process.stderr.write(
            `[tool.closeSession] Error cleaning up session (ID was ${previousSessionId || "default/unknown"}): ${cleanupErrorMessage}\n`,
          );
        }
    
        // Step 2: SessionManager automatically resets to default on cleanup
        // Context.currentSessionId getter will reflect the new active session
        const oldContextSessionId = previousSessionId;
        process.stderr.write(
          `[tool.closeSession] Session context reset to default. Previous context session ID was ${oldContextSessionId || "default/unknown"}.\n`,
        );
    
        // Step 3: Determine the result message
        const defaultSessionId = sessionManager.getDefaultSessionId();
        if (cleanupErrorMessage && !cleanupSuccessful) {
          throw new Error(
            `Failed to cleanup session (session ID was ${previousSessionId || "default/unknown"}). Error: ${cleanupErrorMessage}. Session context has been reset to default.`,
          );
        }
    
        if (cleanupSuccessful) {
          let successMessage = `Browserbase session (${previousSessionId || "default"}) closed successfully. 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 session was found
        let infoMessage =
          "No active session found to close. Session context has been reset to default.";
        if (previousSessionId && previousSessionId !== defaultSessionId) {
          infoMessage = `No active 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 schema for input (empty object) and tool schema definition including name, description, and inputSchema.
    const CloseSessionInputSchema = z.object({});
    
    const closeSessionSchema: ToolSchema<typeof CloseSessionInputSchema> = {
      name: "browserbase_session_close",
      description:
        "Close the current Browserbase session and reset the active context.",
      inputSchema: CloseSessionInputSchema,
    };
  • Defines the tool object combining schema and handler, and exports it as part of sessionTools array for further registration.
    const closeSessionTool: Tool<typeof CloseSessionInputSchema> = {
      capability: "core",
      schema: closeSessionSchema,
      handle: handleCloseSession,
    };
  • Imports sessionTools (containing browserbase_session_close) and includes it in the TOOLS array exported for MCP server registration.
    import sessionTools from "./session.js";
    import getUrlTool from "./url.js";
    
    // Export individual tools
    export { default as navigateTool } from "./navigate.js";
    export { default as actTool } from "./act.js";
    export { default as extractTool } from "./extract.js";
    export { default as observeTool } from "./observe.js";
    export { default as screenshotTool } from "./screenshot.js";
    export { default as sessionTools } from "./session.js";
    export { default as getUrlTool } from "./url.js";
    
    // Export all tools as array
    export const TOOLS = [
      ...sessionTools,
      navigateTool,
      actTool,
      extractTool,
      observeTool,
      screenshotTool,
      getUrlTool,
    ];
  • src/index.ts:186-216 (registration)
    Imports TOOLS, iterates over all tools including browserbase_session_close, and registers each to the MCP server via server.tool(), wrapping the call to context.run(tool, params) which invokes the tool's handle function.
    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?

No annotations are provided, so the description carries the full burden. It discloses that closing resets the active context, which is useful behavioral information, but does not mention potential side effects like data loss, permissions needed, or error handling. It adds some value but lacks comprehensive details.

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, efficient sentence that front-loads the key action ('Close') and purpose. Every word earns its place with no waste, making it highly concise and well-structured.

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 the tool's complexity (simple close operation with no parameters) and lack of annotations/output schema, the description is adequate but minimal. It covers the basic action and context reset, but for a tool that might affect session state, more details on implications or prerequisites could enhance 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 0 parameters with 100% coverage, so no parameter documentation is needed. The description does not add param info, which is appropriate, but baseline is 4 for zero parameters as it avoids redundancy.

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 ('Close') and target resource ('the current Browserbase session'), and distinguishes it from siblings like 'browserbase_session_create' by indicating it terminates rather than initiates a session. It's precise and avoids tautology.

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 ('reset the active context'), suggesting it should be used to clean up after a session, but does not explicitly state when not to use it or name alternatives. It provides clear context without exclusions.

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/kolbertistvan2/stagehand-mcp-server'

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