Skip to main content
Glama

parse_error_log

Parse and compress error logs by extracting essential information and filtering out node_modules frames to reduce token usage.

Instructions

Parses and compresses error logs / stack traces to extract only the essential error information. Filters out node_modules frames, keeps only your source code references. Use this instead of reading raw stderr output to save 90%+ tokens.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
logContentYesThe raw error log / stderr output to compress
workspaceRootNoAbsolute path of the workspace root, used to identify business code frames.
maxFramesNoMaximum number of stack frames to include. Default: 10.

Implementation Reference

  • Core handler function `trimErrorLog` that parses and compresses error logs/stack traces. Extracts error types/messages, filters out node_modules frames, keeps only business code frames up to maxFrames, and returns a compressed summary with stats.
    export function trimErrorLog(
      log: string,
      workspaceRoot?: string,
      maxFrames: number = 10
    ): LogTrimResult {
      const lines = log.split("\n");
      const originalLines = lines.length;
    
      // 1. 提取错误类型和消息
      const errorPattern = /^(\w*Error|\w*Exception|FATAL|PANIC)[:\s]+(.*)$/;
      const errorMatches: Array<{ type: string; message: string; line: number }> = [];
      lines.forEach((line, i) => {
        const match = line.match(errorPattern);
        if (match) errorMatches.push({ type: match[1], message: match[2], line: i });
      });
    
      // 2. 提取堆栈帧,过滤噪音
      const framePattern = /^\s+at\s+(.+?)\s+\((.+?):(\d+):(\d+)\)$/;
      const alternativeFramePattern = /^\s+at\s+(.+?)$/;
      const nodeModulesPattern = /node_modules/;
      const workspacePattern = workspaceRoot
        ? new RegExp(workspaceRoot.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
        : /\/src\//;
    
      const businessFrames: string[] = [];
      let totalFrames = 0;
    
      for (const line of lines) {
        const match = line.match(framePattern);
        if (match) {
          totalFrames++;
          const [, func, file] = match;
          if (!nodeModulesPattern.test(file)) {
            businessFrames.push(line.trim());
          }
          continue;
        }
        const altMatch = line.match(alternativeFramePattern);
        if (altMatch) {
          totalFrames++;
          businessFrames.push(line.trim());
        }
      }
    
      // 3. 组装摘要
      const parts: string[] = [];
    
      if (errorMatches.length > 0) {
        const primary = errorMatches[0];
        parts.push(`[${primary.type}] ${primary.message}`);
        if (errorMatches.length > 1) {
          const secondary = errorMatches[1];
          parts.push(`Caused by: [${secondary.type}] ${secondary.message}`);
        }
      }
    
      if (businessFrames.length > 0) {
        parts.push("\nRelevant stack frames:");
        businessFrames.slice(0, maxFrames).forEach((f) => parts.push(`  ${f}`));
      }
    
      // 4. 添加尾部摘要
      const omittedFrames = totalFrames - Math.min(businessFrames.length, maxFrames);
      if (omittedFrames > 0) {
        parts.push(`  ... ${omittedFrames} frames omitted`);
      }
    
      // 如果没有提取到任何有用信息,返回截断的原始日志
      if (parts.length === 0) {
        const maxLogLines = 50;
        const truncated = lines.slice(0, maxLogLines).join("\n");
        return {
          summary: truncated + (lines.length > maxLogLines ? `\n... [${lines.length - maxLogLines} more lines omitted by ContextGC]` : ""),
          stats: { originalLines, summaryLines: Math.min(lines.length, maxLogLines) },
        };
      }
    
      const summary = parts.join("\n");
      return {
        summary,
        stats: {
          originalLines,
          summaryLines: summary.split("\n").length,
        },
      };
    }
  • Registration of the 'parse_error_log' tool on the MCP server using `server.tool()`. Defines the schema (logContent, workspaceRoot, maxFrames), description, and calls `trimErrorLog` as the handler.
    // ─────────────────────────────────────────────────────
    // Tool 3: parse_error_log
    // ─────────────────────────────────────────────────────
    server.tool(
      "parse_error_log",
      "Parses and compresses error logs / stack traces to extract only the essential error information. Filters out node_modules frames, keeps only your source code references. Use this instead of reading raw stderr output to save 90%+ tokens.",
      {
        logContent: z.string().describe("The raw error log / stderr output to compress"),
        workspaceRoot: z.string().optional().describe("Absolute path of the workspace root, used to identify business code frames."),
        maxFrames: z.number().optional().describe("Maximum number of stack frames to include. Default: 10."),
      },
      async (args): Promise<ToolResult> => {
        const result = trimErrorLog(
          args.logContent,
          args.workspaceRoot,
          args.maxFrames ?? config.logTrimmer.maxFrames
        );
        return {
          content: [{
            type: "text",
            text: result.summary + `\n// [ContextGC] ${result.stats.originalLines} → ${result.stats.summaryLines} lines`,
          }],
        };
      }
    );
  • Zod schema for the tool's input parameters: logContent (required string), workspaceRoot (optional string), maxFrames (optional number).
    {
      logContent: z.string().describe("The raw error log / stderr output to compress"),
      workspaceRoot: z.string().optional().describe("Absolute path of the workspace root, used to identify business code frames."),
      maxFrames: z.number().optional().describe("Maximum number of stack frames to include. Default: 10."),
    },
  • Type definition for `logTrimmer` config, including maxFrames and filterPatterns.
    logTrimmer: {
      maxFrames: number;
      filterPatterns: string[];
    };
  • Default configuration values for logTrimmer: maxFrames=10, filterPatterns=['node_modules', '.next', '.cache', 'dist', 'build'].
    logTrimmer: {
      maxFrames: 10,
      filterPatterns: ["node_modules", ".next", ".cache", "dist", "build"],
    },
Behavior4/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 discloses key behaviors: filters out node_modules frames, keeps only source code references, and compresses to save tokens. It does not mention any destructive actions or side effects, which is appropriate for a parsing tool. However, it could be more explicit about the output format.

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 two sentences long, front-loaded with the main action, and every sentence adds value. No redundant or vague language. It is efficient and easily parseable by an AI agent.

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?

Given the tool's simplicity (parsing logs) and the fact that the schema covers all parameters, the description provides sufficient context. It explains the filtering behavior and token savings. The output format is not described, but it's implied to be a compressed version of the input. No output schema exists, so the description could briefly mention the output structure.

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 baseline is 3. The description adds minimal new semantics beyond the schema; it reinforces the purpose of filtering and compressing but doesn't provide additional detail about parameter constraints or usage nuances.

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 tool parses and compresses error logs/stack traces, with the specific verb 'Parses and compresses' and resource 'error logs / stack traces'. It distinguishes itself by mentioning it filters out node_modules and keeps only source code references, which sets it apart from reading raw stderr.

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

Usage Guidelines4/5

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

The description explicitly says 'Use this instead of reading raw stderr output to save 90%+ tokens', providing clear guidance on when to use this tool. It does not mention when not to use it or alternative tools, but the sibling tools are unrelated, so no further differentiation is necessary.

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/superZavier/contextgc-mcp'

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