Skip to main content
Glama
Winds-AI

autonomous-frontend-browser-tools

browser.console.read

Read and filter browser console logs to capture JavaScript errors, warnings, and network errors with configurable level, time, and search filters.

Instructions

Read browser console logs with filters; returns formatted summary + stats. Captures JS errors/warnings/logs and browser-generated network errors (e.g., 'Failed to load resource'). For full HTTP payloads and headers, use 'browser.network.inspect'.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
levelNoFilter by console message level. Default: 'all'
limitNoMaximum number of entries to return. Default: no limit
timeOffsetNoTime offset in seconds from current time. Use this for relative time filtering (e.g., 10 = last 10 seconds, 300 = last 5 minutes). Maximum allowed: 24 hours (86400 seconds).
searchNoSearch for specific text in console messages

Implementation Reference

  • Registration of the MCP tool 'browser.console.read' with Zod input schema and inline handler function. The handler validates parameters, discovers the browser tools server if needed, constructs query params, and fetches from the backend /console-inspection endpoint, formatting the response.
    server.tool(
      "browser.console.read",
      "Read browser console logs with filters; returns formatted summary + stats. Captures JS errors/warnings/logs and browser-generated network errors (e.g., 'Failed to load resource'). For full HTTP payloads and headers, use 'browser.network.inspect'.",
      {
        level: z
          .enum(["log", "error", "warn", "info", "debug", "all"])
          .optional()
          .describe("Filter by console message level. Default: 'all'"),
        limit: z
          .number()
          .optional()
          .describe("Maximum number of entries to return. Default: no limit"),
        timeOffset: z
          .number()
          .optional()
          .describe(
            "Time offset in seconds from current time. Use this for relative time filtering (e.g., 10 = last 10 seconds, 300 = last 5 minutes). Maximum allowed: 24 hours (86400 seconds)."
          ),
        search: z
          .string()
          .optional()
          .describe("Search for specific text in console messages"),
      },
      async (args) => {
        if (!serverDiscovered) {
          console.error("Server not discovered, attempting discovery...");
          await discoverServer();
          if (!serverDiscovered) {
            return {
              content: [
                {
                  type: "text",
                  text: "❌ Browser Tools Server not found. Please ensure the server is running and the Chrome extension is connected.",
                },
              ],
              isError: true,
            };
          }
        }
    
        try {
          console.error(`Inspecting browser console with filters:`, args);
    
          // Capture current time when tool is called
          const currentTime = Date.now();
          let finalSince: number | undefined;
    
          // Handle timeOffset parameter - calculate relative time
          if (args.timeOffset !== undefined) {
            // Validate timeOffset
            if (args.timeOffset <= 0) {
              throw new Error("timeOffset must be a positive number");
            }
            if (args.timeOffset > 86400) {
              throw new Error("timeOffset cannot exceed 24 hours (86400 seconds)");
            }
    
            // Calculate since timestamp based on offset
            finalSince = currentTime - args.timeOffset * 1000;
    
            console.log(
              `Time offset calculation: ${args.timeOffset}s ago = ${new Date(
                finalSince
              ).toISOString()}`
            );
          }
    
          // Build query parameters
          const queryParams = new URLSearchParams();
          if (args.level) queryParams.append("level", args.level);
          if (args.limit) queryParams.append("limit", args.limit.toString());
          if (finalSince) queryParams.append("since", finalSince.toString());
          if (args.search) queryParams.append("search", args.search);
    
          const url = `http://${discoveredHost}:${discoveredPort}/console-inspection?${queryParams.toString()}`;
          console.error(`Making request to: ${url}`);
    
          const response = await fetch(url, {
            method: "GET",
            headers: {
              "Content-Type": "application/json",
            },
          });
    
          if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
          }
    
          const result = await response.json();
          console.error(
            `Console inspection completed. Found ${
              result.logs?.length || 0
            } entries`
          );
    
          // Format the response for the AI agent
          let responseText = `🔍 **Browser Console Inspection Results**\n\n`;
          responseText += `📊 **Summary**: ${result.summary}\n\n`;
    
          if (result.stats && result.stats.total > 0) {
            responseText += `📈 **Statistics**:\n`;
            responseText += `- Total entries: ${result.stats.total}\n`;
    
            if (result.stats.byLevel) {
              responseText += `- By level: `;
              const levelStats = Object.entries(result.stats.byLevel)
                .map(
                  ([level, count]) => `${count} ${level}${count !== 1 ? "s" : ""}`
                )
                .join(", ");
              responseText += levelStats + "\n";
            }
    
            if (result.stats.timeRange?.oldest && result.stats.timeRange?.newest) {
              const oldestDate = new Date(
                result.stats.timeRange.oldest
              ).toISOString();
              const newestDate = new Date(
                result.stats.timeRange.newest
              ).toISOString();
              responseText += `- Time range: ${oldestDate} to ${newestDate}\n`;
            }
            responseText += "\n";
          }
    
          if (args.level || args.search || args.timeOffset || args.limit) {
            responseText += `🔧 **Applied Filters**:\n`;
            if (args.level) responseText += `- Level: ${args.level}\n`;
            if (args.search) responseText += `- Search: "${args.search}"\n`;
            if (args.timeOffset)
              responseText += `- Time Offset: ${args.timeOffset} seconds ago\n`;
            if (args.limit) responseText += `- Limit: ${args.limit} entries\n`;
            responseText += "\n";
          }
    
          if (result.formatted && result.logs?.length > 0) {
            responseText += `📝 **Console Messages**:\n\n`;
            responseText += result.formatted;
          } else {
            responseText += `â„šī¸ No console messages found matching the specified criteria.`;
          }
    
          return {
            content: [
              {
                type: "text",
                text: responseText,
              },
            ],
          };
        } catch (error: any) {
          const errorMessage =
            error instanceof Error ? error.message : String(error);
          console.error("Console inspection failed:", errorMessage);
    
          return {
            content: [
              {
                type: "text",
                text: `❌ Failed to inspect browser console: ${errorMessage}`,
              },
            ],
            isError: true,
          };
        }
      }
    );
  • Backend HTTP endpoint handler for GET /console-inspection. Parses query filters (level, limit, since, search), calls buildConsoleInspectionResponse helper on stored consoleLogs/errors/warnings arrays, and returns formatted JSON response.
    app.get("/console-inspection", (req, res) => {
      logInfo("Browser Connector: Received console inspection request");
    
      // Parse query parameters for filtering
      const filters: ConsoleFilterParams = {
        level: (req.query.level as any) || "all",
        limit: req.query.limit ? parseInt(req.query.limit as string) : undefined,
        since: req.query.since ? parseInt(req.query.since as string) : undefined,
        search: (req.query.search as string) || undefined,
      };
    
      logDebug("Browser Connector: Console inspection filters:", filters);
    
      try {
        // Build comprehensive console inspection response
        const response = buildConsoleInspectionResponse(
          consoleLogs,
          consoleErrors,
          consoleWarnings,
          filters
        );
    
        logInfo(
          `Browser Connector: Returning ${response.logs.length} console entries`
        );
        logDebug(`Browser Connector: Stats:`, response.stats);
    
        res.json(response);
      } catch (error) {
        console.error("Browser Connector: Error in console inspection:", error);
        res.status(500).json({
          error: error instanceof Error ? error.message : "Unknown error occurred",
        });
      }
    });
  • Core helper function that combines console logs/errors/warnings, applies filters/sorting/limiting, computes stats, formats output, used by backend /console-inspection handler.
    export function buildConsoleInspectionResponse(
      consoleLogs: ConsoleLogEntry[],
      consoleErrors: ConsoleLogEntry[],
      consoleWarnings: ConsoleLogEntry[],
      filters: ConsoleFilterParams = {}
    ): {
      logs: ConsoleLogEntry[];
      stats: ReturnType<typeof getConsoleLogStats>;
      formatted: string;
      summary: string;
      filters: ConsoleFilterParams;
    } {
      // Combine all console entries
      let allLogs: ConsoleLogEntry[] = [];
      
      // Add logs with proper typing
      allLogs.push(...consoleLogs.map(log => ({ ...log, level: 'log' })));
      allLogs.push(...consoleErrors.map(log => ({ ...log, level: 'error' })));
      allLogs.push(...consoleWarnings.map(log => ({ ...log, level: 'warn' })));
    
      // Apply filters
      let filteredLogs = filterConsoleLogs(allLogs, filters);
      
      // Sort by timestamp
      filteredLogs = sortConsoleLogs(filteredLogs);
      
      // Apply limit
      filteredLogs = limitConsoleResults(filteredLogs, filters.limit);
    
      // Get statistics
      const stats = getConsoleLogStats(filteredLogs);
    
      // Format for display
      const { formatted, summary } = formatConsoleLogsForDisplay(filteredLogs);
    
      return {
        logs: filteredLogs,
        stats,
        formatted,
        summary,
        filters
      };
    }
  • Code in /extension-log POST endpoint that receives console events from Chrome extension (console-log/error/warn) and stores them in in-memory arrays consoleLogs, consoleErrors, consoleWarnings (with size limiting). These arrays are used by /console-inspection.
    case "console-log":
      logDebug("Adding console log:", {
        level: data.level,
        message:
          data.message?.substring(0, 100) +
          (data.message?.length > 100 ? "..." : ""),
        timestamp: data.timestamp,
      });
      consoleLogs.push(data);
      if (consoleLogs.length > currentSettings.logLimit) {
        logDebug(
          `Console logs exceeded limit (${currentSettings.logLimit}), removing oldest entry`
        );
        consoleLogs.shift();
      }
      break;
    case "console-error":
      logDebug("Adding console error:", {
        level: data.level,
        message:
          data.message?.substring(0, 100) +
          (data.message?.length > 100 ? "..." : ""),
        timestamp: data.timestamp,
      });
      consoleErrors.push(data);
      if (consoleErrors.length > currentSettings.logLimit) {
        logDebug(
          `Console errors exceeded limit (${currentSettings.logLimit}), removing oldest entry`
        );
        consoleErrors.shift();
      }
      break;
    case "console-warn":
      logDebug("Adding console warning:", {
        level: data.level,
        message:
          data.message?.substring(0, 100) +
          (data.message?.length > 100 ? "..." : ""),
        timestamp: data.timestamp,
      });
      consoleWarnings.push(data);
      if (consoleWarnings.length > currentSettings.logLimit) {
        logDebug(
          `Console warnings exceeded limit (${currentSettings.logLimit}), removing oldest entry`
        );
        consoleWarnings.shift();
      }
      break;
  • Zod input schema defining parameters for the browser.console.read tool: level (enum), limit (number), timeOffset (number), search (string).
    {
      level: z
        .enum(["log", "error", "warn", "info", "debug", "all"])
        .optional()
        .describe("Filter by console message level. Default: 'all'"),
      limit: z
        .number()
        .optional()
        .describe("Maximum number of entries to return. Default: no limit"),
      timeOffset: z
        .number()
        .optional()
        .describe(
          "Time offset in seconds from current time. Use this for relative time filtering (e.g., 10 = last 10 seconds, 300 = last 5 minutes). Maximum allowed: 24 hours (86400 seconds)."
        ),
      search: z
        .string()
        .optional()
        .describe("Search for specific text in console messages"),
    },

Schema Changelog

Changes observed during successful MCP inspections. Dates show when Glama detected each change.

  1. First observed

TDQS

A4.4/5.0
Behavior4/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 effectively describes what the tool captures (JS errors/warnings/logs, browser-generated network errors) and what it returns (formatted summary + stats). However, it doesn't mention potential limitations like whether it clears logs after reading, requires specific browser state, or has rate limits.

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 perfectly concise with two sentences that each earn their place. The first sentence states the core functionality and return value, while the second provides crucial sibling differentiation. There's zero wasted text.

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

Completeness4/5

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

For a read-only tool with 4 parameters and no output schema, the description provides good context about what's captured and returned, plus sibling differentiation. However, without annotations or output schema, it could benefit from more detail about the return format (what 'formatted summary + stats' means) and any behavioral constraints.

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 schema description coverage is 100%, so all parameters are documented in the schema. The description doesn't add any parameter-specific information beyond what's in the schema. According to guidelines, when schema coverage is high (>80%), the baseline score is 3 even with no param info in the description.

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 ('Read browser console logs with filters') and resource ('browser console logs'), and explicitly distinguishes it from sibling 'browser.network.inspect' for full HTTP payloads. It specifies what types of logs are captured (JS errors/warnings/logs and browser-generated network errors).

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit guidance on when to use this tool vs. alternatives: 'For full HTTP payloads and headers, use 'browser.network.inspect''. This clearly defines the boundary between this console-focused tool and the network-focused sibling tool.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

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/Winds-AI/Frontend-development-MCP-tools-public'

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