Skip to main content
Glama

playwright_console_logs

Retrieve and filter browser console logs during automation testing to identify errors, warnings, and debug information with search and limit options.

Instructions

Retrieve console logs from the browser with filtering options

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
typeNoType of logs to retrieve (all, error, warning, log, info, debug, exception)
searchNoText to search for in logs (handles text with square brackets)
limitNoMaximum number of logs to return
clearNoWhether to clear logs after retrieval (default: false)

Implementation Reference

  • The execute method of ConsoleLogsTool that filters stored console logs by type, search term, limit, and optionally clears them. Saves the filtered logs to a temporary file, registers it as a resource, and returns the result.
    async execute(args: any, _context: ToolContext): Promise<ToolResponse> {
      // No need to use safeExecute here as we don't need to interact with the page
      // We're just filtering and returning logs that are already stored
    
      let logs = [...this.consoleLogs];
    
      // Filter by type if specified
      if (args.type && args.type !== "all") {
        logs = logs.filter((log) => log.startsWith(`[${args.type}]`));
      }
    
      // Filter by search text if specified
      if (args.search) {
        logs = logs.filter((log) => log.includes(args.search));
      }
    
      // Limit the number of logs if specified
      if (args.limit && args.limit > 0) {
        logs = logs.slice(-args.limit);
      }
    
      // Clear logs if requested
      if (args.clear) {
        this.consoleLogs = [];
      }
    
      // Format the response
      if (logs.length === 0) {
        return createSuccessResponse("No console logs matching the criteria");
      } else {
        let savedLocation: string | undefined;
        let resourceLink: Awaited<ReturnType<typeof registerFileResource>> | undefined;
        try {
          const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
          const filename = `console-logs-${timestamp}.txt`;
          const tempPath = path.join(process.cwd(), filename);
          await fs.writeFile(tempPath, logs.join("\n"), "utf-8");
          resourceLink = await registerFileResource({
            filePath: tempPath,
            name: filename,
            mimeType: "text/plain",
            server: this.server,
          });
          savedLocation = resourceLink?.uri ?? tempPath;
          await fs.unlink(tempPath).catch(() => {});
        } catch (_error) {
          // If resource registration fails, just include inline logs
          savedLocation = undefined;
        }
    
        return {
          ...createSuccessResponse(
            savedLocation ? [`Retrieved ${logs.length} console log(s). Download: ${savedLocation}`, ...logs] : logs,
          ),
          ...(resourceLink ? { resourceLinks: [resourceLink] } : {}),
        };
      }
    }
  • Defines the tool's name, description, and input schema for parameters: type (enum), search (string), limit (number), clear (boolean).
      name: "playwright_console_logs",
      description: "Retrieve console logs from the browser with filtering options",
      inputSchema: {
        type: "object",
        properties: {
          type: {
            type: "string",
            description: "Type of logs to retrieve (all, error, warning, log, info, debug, exception)",
            enum: ["all", "error", "warning", "log", "info", "debug", "exception"],
          },
          search: {
            type: "string",
            description: "Text to search for in logs (handles text with square brackets)",
          },
          limit: {
            type: "number",
            description: "Maximum number of logs to return",
          },
          clear: {
            type: "boolean",
            description: "Whether to clear logs after retrieval (default: false)",
          },
        },
        required: [],
      },
    },
  • Switch case in handleToolCall that dispatches the tool call to the consoleLogsTool instance's execute method.
    case "playwright_console_logs":
      return await consoleLogsTool.execute(args, context);
  • Instantiates the ConsoleLogsTool instance during tool initialization if not already created.
    if (!consoleLogsTool) consoleLogsTool = new ConsoleLogsTool(server);
  • ConsoleLogsTool class definition including methods to register, get, and clear console logs.
    export class ConsoleLogsTool extends BrowserToolBase {
      private consoleLogs: string[] = [];
    
      /**
       * Register a console message
       * @param type The type of console message
       * @param text The text content of the message
       */
      registerConsoleMessage(type: string, text: string): void {
        const logEntry = `[${type}] ${text}`;
        this.consoleLogs.push(logEntry);
      }
    
      /**
       * Execute the console logs tool
       */
      async execute(args: any, _context: ToolContext): Promise<ToolResponse> {
        // No need to use safeExecute here as we don't need to interact with the page
        // We're just filtering and returning logs that are already stored
    
        let logs = [...this.consoleLogs];
    
        // Filter by type if specified
        if (args.type && args.type !== "all") {
          logs = logs.filter((log) => log.startsWith(`[${args.type}]`));
        }
    
        // Filter by search text if specified
        if (args.search) {
          logs = logs.filter((log) => log.includes(args.search));
        }
    
        // Limit the number of logs if specified
        if (args.limit && args.limit > 0) {
          logs = logs.slice(-args.limit);
        }
    
        // Clear logs if requested
        if (args.clear) {
          this.consoleLogs = [];
        }
    
        // Format the response
        if (logs.length === 0) {
          return createSuccessResponse("No console logs matching the criteria");
        } else {
          let savedLocation: string | undefined;
          let resourceLink: Awaited<ReturnType<typeof registerFileResource>> | undefined;
          try {
            const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
            const filename = `console-logs-${timestamp}.txt`;
            const tempPath = path.join(process.cwd(), filename);
            await fs.writeFile(tempPath, logs.join("\n"), "utf-8");
            resourceLink = await registerFileResource({
              filePath: tempPath,
              name: filename,
              mimeType: "text/plain",
              server: this.server,
            });
            savedLocation = resourceLink?.uri ?? tempPath;
            await fs.unlink(tempPath).catch(() => {});
          } catch (_error) {
            // If resource registration fails, just include inline logs
            savedLocation = undefined;
          }
    
          return {
            ...createSuccessResponse(
              savedLocation ? [`Retrieved ${logs.length} console log(s). Download: ${savedLocation}`, ...logs] : logs,
            ),
            ...(resourceLink ? { resourceLinks: [resourceLink] } : {}),
          };
        }
      }
    
      /**
       * Get all console logs
       */
      getConsoleLogs(): string[] {
        return this.consoleLogs;
      }
    
      /**
       * Clear all console logs
       */
      clearConsoleLogs(): void {
        this.consoleLogs = [];
      }
    }
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 mentions 'retrieve' and 'filtering options' but fails to disclose critical traits such as whether this operation is safe (read-only vs. potentially destructive), if it requires specific browser states, or how logs are structured in the response. The mention of 'clear' in the schema hints at potential side effects, but the description doesn't address this.

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 purpose ('retrieve console logs') and briefly mentions key features ('from the browser with filtering options'). There is no wasted verbiage, making it highly concise and well-structured for quick comprehension.

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 complexity of a browser logging tool with no annotations and no output schema, the description is insufficient. It lacks details on behavioral aspects (e.g., side effects, prerequisites), output format, or error handling, leaving significant gaps for an agent to understand how to use this tool effectively in context.

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?

Schema description coverage is 100%, so the schema fully documents all four parameters. The description adds minimal value beyond the schema by implying filtering capabilities ('with filtering options'), but it doesn't elaborate on parameter interactions or provide additional semantic context. This meets the baseline 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 verb ('retrieve') and resource ('console logs from the browser'), making the purpose unambiguous. However, it doesn't explicitly differentiate from sibling tools like playwright_get_visible_html or playwright_get_visible_text, which also retrieve browser content but of different types.

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 mentions 'filtering options' but doesn't specify scenarios where filtering logs is preferable over other retrieval methods or when this tool should be avoided, leaving the agent without contextual usage cues.

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