Skip to main content
Glama

end_codegen_session

End a Playwright browser automation code generation session and produce the final test file by providing the session ID.

Instructions

End a code generation session and generate the test file

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sessionIdYesID of the session to end

Implementation Reference

  • Primary handler implementation for end_codegen_session tool. Ends the recording session, generates Playwright test using PlaywrightGenerator, writes file to disk, optionally registers as MCP resource, cleans up browser state, and returns file information.
    export const endCodegenSession: Tool = {
      name: "end_codegen_session",
      description: "End the current code generation session and generate Playwright test",
      parameters: {
        type: "object",
        properties: {
          sessionId: {
            type: "string",
            description: "ID of the session to end",
          },
        },
        required: ["sessionId"],
      },
      handler: async ({ sessionId }: { sessionId: string }, context?: { server?: any }) => {
        try {
          const recorder = ActionRecorder.getInstance();
          const session = recorder.endSession(sessionId);
    
          if (!session) {
            throw new Error(`Session ${sessionId} not found`);
          }
    
          if (!session.options) {
            throw new Error(`Session ${sessionId} has no options configured`);
          }
    
          const generator = new PlaywrightGenerator(session.options);
          const result = await generator.generateTest(session);
    
          // Double check output directory exists
          const outputDir = path.dirname(result.filePath);
          await fs.mkdir(outputDir, { recursive: true });
    
          // Write test file
          try {
            await fs.writeFile(result.filePath, result.testCode, "utf-8");
          } catch (writeError: any) {
            throw new Error(`Failed to write test file: ${writeError.message}`);
          }
    
          let resourceLink: Awaited<ReturnType<typeof registerFileResource>> | undefined;
          try {
            resourceLink = await registerFileResource({
              filePath: result.filePath,
              name: path.basename(result.filePath),
              mimeType: "text/plain",
              server: context?.server,
            });
          } catch (error) {
            console.warn("Failed to register generated test as resource:", error);
          }
    
          // Close Playwright browser and cleanup
          try {
            if (global.browser?.isConnected()) {
              await global.browser.close();
            }
          } catch (browserError: any) {
            console.warn("Failed to close browser:", browserError.message);
          } finally {
            global.browser = undefined;
            global.page = undefined;
          }
    
          const absolutePath = path.resolve(result.filePath);
          const displayPath = resourceLink?.uri ?? absolutePath;
    
          return {
            filePath: absolutePath,
            outputDirectory: outputDir,
            testCode: result.testCode,
            message: `Generated test file at: ${displayPath}\nOutput directory: ${outputDir}`,
            ...(resourceLink ? { resourceLinks: [resourceLink] } : {}),
          };
        } catch (error: any) {
          // Ensure browser cleanup even on error
          try {
            if (global.browser?.isConnected()) {
              await global.browser.close();
            }
          } catch {
            // Ignore cleanup errors
          } finally {
            global.browser = undefined;
            global.page = undefined;
          }
    
          throw new Error(`Failed to end codegen session: ${error.message}`);
        }
      },
    };
  • Input schema definition for end_codegen_session used in MCP tool definitions list (createToolDefinitions). Defines parameters and validation.
    {
      name: "end_codegen_session",
      description: "End a code generation session and generate the test file",
      inputSchema: {
        type: "object",
        properties: {
          sessionId: {
            type: "string",
            description: "ID of the session to end",
          },
        },
        required: ["sessionId"],
      },
    },
  • Tool dispatch/registration in main tool handler switch statement. Imports endCodegenSession from codegen/index.ts and calls its handler via handleCodegenResult.
    case "end_codegen_session":
      return await handleCodegenResult(endCodegenSession.handler(args, { server }));
  • Import statement bringing endCodegenSession handler into toolHandler.ts for use in dispatch.
      clearCodegenSession,
      endCodegenSession,
      getCodegenSession,
      startCodegenSession,
    } from "./tools/codegen/index.js";
  • Input parameters schema defined directly in the tool object (matches tools.ts schema). Used by the handler.
    parameters: {
      type: "object",
      properties: {
        sessionId: {
          type: "string",
          description: "ID of the session to end",
        },
      },
      required: ["sessionId"],
    },
Behavior2/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 states the tool ends a session and generates a test file, but lacks details on permissions, side effects (e.g., if the session is deleted or archived), or error handling, which is insufficient 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, efficient sentence that directly states the tool's purpose without unnecessary words. It is front-loaded and wastes no space, earning a perfect score for conciseness.

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

Completeness2/5

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

Given the tool's complexity as a mutation operation with no annotations and no output schema, the description is incomplete. It fails to explain what 'generate the test file' entails (e.g., format, location, or success criteria), leaving significant gaps for the agent.

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

Parameters3/5

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

The input schema has 100% description coverage, clearly documenting the 'sessionId' parameter. The description adds no additional parameter details beyond what the schema provides, so it meets the baseline score of 3 for high schema coverage.

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 action ('End') and resource ('a code generation session'), and mentions generating a test file as an outcome. However, it doesn't explicitly differentiate from sibling tools like 'clear_codegen_session' or 'get_codegen_session', which prevents a perfect score.

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 provides no guidance on when to use this tool versus alternatives, such as 'clear_codegen_session' or 'get_codegen_session', nor does it mention prerequisites like needing an active session. This leaves the agent without context for selection.

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/aakashH242/mcp-playwright'

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