Skip to main content
Glama

get-console-logs

Retrieve console logs from the Vite development server. Optionally filter by checkpoint or limit to recent logs for debugging and monitoring.

Instructions

Retrieves console logs from the development server

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
checkpointNoIf specified, returns only logs recorded at this checkpoint
limitNoNumber of logs to return, starting from the most recent log

Implementation Reference

  • The actual tool handler for 'get-console-logs'. It reads logs using LogManager.readLogs(), parses them from JSON, and returns them with write position and total log count.
    // Console logs retrieval tool
    server.tool(
      'get-console-logs',
      'Retrieves console logs from the development server',
      {
        checkpoint: z.string().optional().describe('If specified, returns only logs recorded at this checkpoint'),
        limit: z.number().optional().describe('Number of logs to return, starting from the most recent log')
      },
      async ({ checkpoint, limit = 100 }) => {
        try {
          // Read logs (always provide limit value)
          const result = await logManager.readLogs(limit, checkpoint);
    
          // Parse logs
          const parsedLogs = result.logs.map((log: string) => {
            try {
              return JSON.parse(log);
            } catch (error) {
              return { type: 'unknown', text: log, timestamp: new Date().toISOString() };
            }
          });
    
          return {
            content: [
              {
                type: 'text',
                text: JSON.stringify({
                  logs: parsedLogs,
                  writePosition: result.writePosition,
                  totalLogs: result.totalLogs
                }, null, 2)
              }
            ]
          };
        } catch (error) {
          Logger.error(`Failed to read console logs: ${error}`);
          return {
            content: [
              {
                type: 'text',
                text: `Failed to read console logs: ${error}`
              }
            ],
            isError: true
          };
        }
      }
    );
  • Input schema for 'get-console-logs' tool: optional 'checkpoint' (string) to filter by checkpoint ID, and optional 'limit' (number, default 100) for number of logs to return.
    'Retrieves console logs from the development server',
    {
      checkpoint: z.string().optional().describe('If specified, returns only logs recorded at this checkpoint'),
      limit: z.number().optional().describe('Number of logs to return, starting from the most recent log')
    },
  • The tool is registered inside registerBrowserTools() using server.tool('get-console-logs', ...) in src/tools/browser-tools.ts, which is called from src/index.ts at line 87.
    // Console logs retrieval tool
    server.tool(
      'get-console-logs',
      'Retrieves console logs from the development server',
      {
        checkpoint: z.string().optional().describe('If specified, returns only logs recorded at this checkpoint'),
        limit: z.number().optional().describe('Number of logs to return, starting from the most recent log')
      },
      async ({ checkpoint, limit = 100 }) => {
        try {
          // Read logs (always provide limit value)
          const result = await logManager.readLogs(limit, checkpoint);
    
          // Parse logs
          const parsedLogs = result.logs.map((log: string) => {
            try {
              return JSON.parse(log);
            } catch (error) {
              return { type: 'unknown', text: log, timestamp: new Date().toISOString() };
            }
          });
    
          return {
            content: [
              {
                type: 'text',
                text: JSON.stringify({
                  logs: parsedLogs,
                  writePosition: result.writePosition,
                  totalLogs: result.totalLogs
                }, null, 2)
              }
            ]
          };
        } catch (error) {
          Logger.error(`Failed to read console logs: ${error}`);
          return {
            content: [
              {
                type: 'text',
                text: `Failed to read console logs: ${error}`
              }
            ],
            isError: true
          };
        }
      }
    );
  • The LogManager.readLogs() helper method that reads logs from files, supporting filtering by checkpoint ID and limiting the number of logs returned.
    public async readLogs(limit: number, checkpointId?: string): Promise<{ logs: string[], writePosition: number, totalLogs: number }> {
      try {
        // 1. Calculate necessary information
        const logDir = path.dirname(this.getLogFilePath(0, checkpointId));
        const filePattern = checkpointId ?
          new RegExp(`^chk-${checkpointId}-(\\d+)\\.log$`) :
          /^default-log-(\d+)\.log$/;
    
        // 2. Find log files in directory
        const files = fs.existsSync(logDir) ? fs.readdirSync(logDir) : [];
        const logFiles = files
          .filter(file => filePattern.test(file))
          .map(file => {
            const match = file.match(filePattern);
            return {
              file,
              path: path.join(logDir, file),
              number: match ? parseInt(match[1], 10) : -1
            };
          })
          .filter(item => item.number >= 0)
          .sort((a, b) => a.number - b.number); // Sort in order (oldest first)
    
        if (logFiles.length === 0) {
          return { logs: [], writePosition: 0, totalLogs: 0 };
        }
    
        // 3. Calculate total number of logs (completed files + current file log count)
        const lastFileIndex = logFiles.length - 1;
        const completedFilesLogs = lastFileIndex * this.MAX_LOGS_PER_FILE;
    
        // Get log count of the last file
        let currentFileLogCount = 0;
        if (checkpointId) {
          const checkpointData = this.checkpointStreams.get(checkpointId);
          currentFileLogCount = checkpointData ? checkpointData.currentLogCount : 0;
        } else {
          currentFileLogCount = this.currentLogCount;
        }
    
        const totalLogs = completedFilesLogs + currentFileLogCount;
    
        // 4. Return empty result if no logs needed
        if (totalLogs === 0) {
          return { logs: [], writePosition: currentFileLogCount, totalLogs: 0 };
        }
    
        // 5. Calculate start position and number of logs to read
        const startPosition = Math.max(0, totalLogs - limit);
        const startFileIndex = Math.floor(startPosition / this.MAX_LOGS_PER_FILE);
        const startLogInFile = startPosition % this.MAX_LOGS_PER_FILE;
    
        // 6. Read log files (using stream)
        const logs: string[] = [];
        let logsNeeded = Math.min(limit, totalLogs);
    
        for (let i = startFileIndex; i < logFiles.length && logsNeeded > 0; i++) {
          const filePath = logFiles[i].path;
          if (!fs.existsSync(filePath)) continue;
    
          // Read line by line using readline interface
          const rl = readline.createInterface({
            input: fs.createReadStream(filePath, { encoding: 'utf-8' }),
            crlfDelay: Infinity
          });
    
          let skippedLines = 0;
    
          // Skip lines if this is the first file and has a start position
          const shouldSkipLines = (i === startFileIndex && startLogInFile > 0);
          const linesToSkip = shouldSkipLines ? startLogInFile : 0;
    
          for await (const line of rl) {
            if (!line.trim()) continue;
    
            // Skip necessary lines
            if (shouldSkipLines && skippedLines < linesToSkip) {
              skippedLines++;
              continue;
            }
    
            logs.push(line);
            logsNeeded--;
    
            if (logsNeeded <= 0) {
              rl.close();
              break;
            }
          }
        }
    
        // 7. Return result
        return {
          logs,
          writePosition: currentFileLogCount,
          totalLogs
        };
      } catch (error) {
        Logger.error(`Failed to read logs: ${error}`);
        return { logs: [], writePosition: 0, totalLogs: 0 };
      }
    }
  • The LogManager.appendLog() helper method that writes console log entries to both default and checkpoint-specific log files.
    public async appendLog(logEntry: string, checkpointId?: string): Promise<void> {
      try {
        // Append log to default log file
        await new Promise<void>((resolve, reject) => {
          const writeStream = this.writeStream;
    
          if (!writeStream) {
            reject(new Error('Log file is not initialized'));
            return;
          }
    
          this.writeStream?.write(logEntry, (err: Error | null | undefined) => {
            if (err) { reject(err); } else {
              this.currentLogCount++;
    
              if (this.currentLogCount >= this.MAX_LOGS_PER_FILE) {
                this.initializeLogFile({ nextFileNumber: this.currentFileNumber + 1 });
              }
    
              resolve();
            }
          });
        });
    
        // Append log to checkpoint log file
        if (checkpointId) {
          if (!this.checkpointStreams.has(checkpointId)) {
            this.initializeLogFile({ checkpointId });
          } else if (this.isCheckpointStreamAttached(checkpointId) === false) {
            await this.attachCheckpointStream(checkpointId);
          }
    
          await this.detachCheckpointStreams();
        }
    
        if (checkpointId) {
          await new Promise<void>((resolve, reject) => {
            const streamData = this.checkpointStreams.get(checkpointId);
    
            if (!streamData) {
              reject(new Error('Checkpoint stream data not found'));
              return;
            }
    
            streamData.writeStream?.write(logEntry, (err: Error | null | undefined) => {
              if (err) { reject(err); } else {
                streamData.currentLogCount++;
    
                if (streamData.currentLogCount >= this.MAX_LOGS_PER_FILE) {
                  this.initializeLogFile({ nextFileNumber: streamData.currentFileNumber + 1, checkpointId });
                }
    
                resolve();
              }
            });
          });
        }
      } catch (error) {
        Logger.error(`Failed to append log: ${error}`);
      }
    }

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observed

TDQS

B3.3/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the burden of disclosing behavior. It establishes a read-oriented retrieval action and specifies the source as the development server, but it does not describe whether logs are paginated, what 'limit' does exactly, what a checkpoint is, or how the returned logs are structured.

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, front-loaded sentence with no wasted words. It names the action, the target, and the environment in a compact way.

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?

For a simple tool with two optional, fully described parameters, the description is minimally viable. However, it lacks any statement about expected return shape, prerequisites such as a running development server, or when not to use this tool, and there is no output schema or annotations to cover those gaps.

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 already documents both parameters with 100% coverage, so the description adds little parameter-level meaning. The description does not explain how limit and checkpoint interact, but the schema descriptions are sufficiently detailed to set a baseline of 3.

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 uses a specific verb ('Retrieves') and a specific resource ('console logs'), and 'from the development server' gives scope. It does not explicitly contrast with sibling tools like get-hmr-events or get-context-stats, but the resource name is distinct enough to make the tool's purpose identifiable.

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 gives no guidance about when to prefer this tool over alternatives. There is no mention of use cases, exclusions, or sibling tools, so an agent is left to infer context purely from the name and the short description.

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