Skip to main content
Glama
MesuterPikin

Browserbase MCP Server

by MesuterPikin

browserbase_session_close

Ends the current browser automation session to reset the active context and free resources.

Instructions

Close the current Browserbase session and reset the active context.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The primary handler function that executes the tool's logic: retrieves the current session ID, attempts to clean up the session using SessionManager, handles cases where no session exists, logs details, and returns appropriate text content responses.
    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,
      };
    }
  • Defines the Zod input schema (empty, no parameters required) and the tool schema with name and description for the browserbase_session_close tool.
    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,
    };
  • Registers the session tools (including browserbase_session_close from sessionTools) into the central TOOLS array, likely used by the MCP server to expose available tools.
    export const TOOLS = [
      ...sessionTools,
      navigateTool,
      actTool,
      extractTool,
      observeTool,
      screenshotTool,
      getUrlTool,
      agentTool,
    ];
  • Assembles the complete tool object by combining the schema, handler function, and capability for browserbase_session_close.
    const closeSessionTool: Tool<typeof CloseSessionInputSchema> = {
      capability: "core",
      schema: closeSessionSchema,
      handle: handleCloseSession,
    };
  • Supporting helper method in SessionManager called by the tool handler to perform the actual session cleanup and closure.
    async cleanupSession(sessionId: string): Promise<void> {
      process.stderr.write(
        `[SessionManager] Cleaning up session: ${sessionId}\n`,
      );
    
      // Get the session to close it gracefully
      const session = this.browsers.get(sessionId);
      if (session) {
        await this.closeBrowserGracefully(session, sessionId);
      }
    
      // Remove from browsers map
      this.browsers.delete(sessionId);
    
      // Clear default session reference if this was the default
      if (sessionId === this.defaultSessionId && this.defaultBrowserSession) {
        this.defaultBrowserSession = null;
      }
    
      // Reset active session to default if this was the active one
      if (this.activeSessionId === sessionId) {
        process.stderr.write(
          `[SessionManager] Cleaned up active session ${sessionId}, resetting to default.\n`,
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 that the tool closes a session and resets context, which implies a destructive action (ending an active session) but does not detail effects like data loss, cleanup behavior, or error handling. This provides basic behavioral insight but lacks depth for a mutation 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 a single, clear sentence that is front-loaded with the core action ('Close the current Browserbase session') and adds necessary context ('and reset the active context'). There is no wasted verbiage, making it highly efficient 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 (a mutation with no annotations and no output schema), the description is minimal but covers the essential action. It lacks details on what 'reset the active context' entails, potential side effects, or return values, which could be important for an agent using this tool effectively.

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 parameters, which is appropriate, and thus adds no value beyond the schema. Baseline is 4 for zero parameters, as it avoids unnecessary detail.

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 resource ('the current Browserbase session'), and distinguishes it from siblings by mentioning 'reset the active context' which is unique among the listed tools. It precisely communicates what the tool does without being tautological.

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 referring to 'the current Browserbase session,' suggesting it should be used when a session is active and needs termination. However, it does not explicitly state when not to use it or name alternatives, such as whether other tools might handle session management differently.

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

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