Skip to main content
Glama
pvinis
by pvinis

end_codegen_session

Terminate a code generation session and produce the final test file. Uses the session ID to ensure proper closure and file generation within the Playwright MCP Server environment.

Instructions

End a code generation session and generate the test file

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sessionIdYesID of the session to end

Implementation Reference

  • The core handler function that terminates the codegen session: ends the session via ActionRecorder, generates Playwright test code using PlaywrightGenerator, writes the test file to disk, and cleans up global browser/page instances.
    handler: async ({ sessionId }: { sessionId: string }) => {
      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}`);
        }
    
        // 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);
    
        return {
          filePath: absolutePath,
          outputDirectory: outputDir,
          testCode: result.testCode,
          message: `Generated test file at: ${absolutePath}\nOutput directory: ${outputDir}`,
        };
      } 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 the end_codegen_session tool, specifying the required sessionId parameter.
    parameters: {
      type: "object",
      properties: {
        sessionId: {
          type: "string",
          description: "ID of the session to end",
        },
      },
      required: ["sessionId"],
    },
  • Registration in the main tool handler switch statement that dispatches calls to the endCodegenSession.handler function.
    case "end_codegen_session":
      return await handleCodegenResult(endCodegenSession.handler(args));
  • src/tools.ts:37-49 (registration)
    Tool registration schema in createToolDefinitions() for MCP tool list, including name, description, and inputSchema.
      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"]
      }
    },
  • Helper function used to wrap and format the result of codegen tool handlers, including end_codegen_session.
    async function handleCodegenResult(
      resultPromise: Promise<any>
    ): Promise<CallToolResult> {
      try {
        const result = await resultPromise;
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(result),
            },
          ],
          isError: false,
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: error instanceof Error ? error.message : String(error),
            },
          ],
          isError: true,
        };
      }
    }
Behavior2/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 mentions ending a session and generating a test file, but lacks details on behavioral traits: it doesn't specify if this is destructive (e.g., deletes session data), what permissions are needed, how the test file is generated (e.g., format, location), or error handling. The description is too vague for a mutation tool with zero annotation coverage.

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 core action ('End a code generation session') and adds a secondary outcome ('and generate the test file'). There is no wasted language, and it's appropriately sized for the tool's complexity.

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 (a mutation with no annotations and no output schema), the description is incomplete. It doesn't explain what 'ending' entails (e.g., cleanup, persistence), how the test file is generated or returned, or potential side effects. For a tool that modifies state and produces output, more context is needed to be fully helpful.

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, with 'sessionId' clearly documented. The description adds no parameter-specific information beyond what the schema provides (e.g., no details on sessionId format or validation). With high schema coverage, the baseline is 3, as the description doesn't compensate but also doesn't detract.

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 ('End') and resource ('a code generation session'), and specifies an additional action ('generate the test file'). It distinguishes from siblings like 'clear_codegen_session' (which likely clears without generating) and 'get_codegen_session' (which retrieves without ending). However, it doesn't explicitly differentiate from all siblings, keeping it at 4 rather than 5.

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. It doesn't mention prerequisites (e.g., needing an active session from 'start_codegen_session'), exclusions, or comparisons to siblings like 'clear_codegen_session'. Usage is implied but not explicitly stated, resulting in minimal guidance.

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

Related 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/pvinis/mcp-playwright-stealth'

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