Skip to main content
Glama

track_documentation_freshness

Scan documentation directories to identify outdated files using configurable time thresholds, helping maintain current documentation by flagging content needing updates.

Instructions

Scan documentation directory for staleness markers and identify files needing updates based on configurable time thresholds (minutes, hours, days)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
docsPathYesPath to documentation directory
projectPathNoPath to project root (for knowledge graph tracking)
warningThresholdNoWarning threshold (yellow flag)
staleThresholdNoStale threshold (orange flag)
criticalThresholdNoCritical threshold (red flag)
presetNoUse predefined threshold preset
includeFileListNoInclude detailed file list in response
sortByNoSort order for file liststaleness
storeInKGNoStore tracking event in knowledge graph for historical analysis

Implementation Reference

  • The main handler function for the 'track_documentation_freshness' tool. It processes input parameters, determines staleness thresholds, scans documentation using scanDocumentationFreshness, optionally stores results in knowledge graph, formats a comprehensive report, and returns structured MCPToolResponse.
    export async function trackDocumentationFreshness(
      input: TrackDocumentationFreshnessInput,
    ): Promise<MCPToolResponse> {
      const startTime = Date.now();
    
      try {
        const {
          docsPath,
          projectPath,
          warningThreshold,
          staleThreshold,
          criticalThreshold,
          preset,
          includeFileList,
          sortBy,
          storeInKG,
        } = input;
    
        // Determine thresholds
        let thresholds: {
          warning?: StalenessThreshold;
          stale?: StalenessThreshold;
          critical?: StalenessThreshold;
        } = {};
    
        if (preset) {
          // Use preset thresholds
          const presetThreshold = STALENESS_PRESETS[preset];
          thresholds = {
            warning: presetThreshold,
            stale: { value: presetThreshold.value * 2, unit: presetThreshold.unit },
            critical: {
              value: presetThreshold.value * 3,
              unit: presetThreshold.unit,
            },
          };
        } else {
          // Use custom thresholds
          if (warningThreshold) thresholds.warning = warningThreshold;
          if (staleThreshold) thresholds.stale = staleThreshold;
          if (criticalThreshold) thresholds.critical = criticalThreshold;
        }
    
        // Scan documentation
        const report = await scanDocumentationFreshness(docsPath, thresholds);
    
        // Store in knowledge graph if requested and projectPath provided
        let kgInsights:
          | Awaited<ReturnType<typeof getStalenessInsights>>
          | undefined;
        if (storeInKG !== false && projectPath) {
          try {
            await storeFreshnessEvent(projectPath, docsPath, report, "scan");
            kgInsights = await getStalenessInsights(projectPath);
          } catch (error) {
            // KG storage failed, but continue with the response
            console.warn(
              "Failed to store freshness event in knowledge graph:",
              error,
            );
          }
        }
    
        // Format response
        const formattedReport = formatFreshnessReport(
          report,
          includeFileList ?? true,
          sortBy ?? "staleness",
        );
    
        // Add KG insights to formatted report if available
        let enhancedReport = formattedReport;
        if (kgInsights && kgInsights.totalEvents > 0) {
          enhancedReport += "\n## Historical Insights\n\n";
          enhancedReport += `- **Total tracking events**: ${kgInsights.totalEvents}\n`;
          enhancedReport += `- **Average improvement score**: ${(
            kgInsights.averageImprovementScore * 100
          ).toFixed(1)}%\n`;
          enhancedReport += `- **Trend**: ${
            kgInsights.trend === "improving"
              ? "📈 Improving"
              : kgInsights.trend === "declining"
                ? "📉 Declining"
                : "➡️ Stable"
          }\n\n`;
    
          if (kgInsights.recommendations.length > 0) {
            enhancedReport += "### Knowledge Graph Insights\n\n";
            for (const rec of kgInsights.recommendations) {
              enhancedReport += `${rec}\n\n`;
            }
          }
        }
    
        // Convert KG insights to Recommendation objects
        const recommendations =
          kgInsights?.recommendations.map((rec) => {
            // Determine type based on content
            let type: "info" | "warning" | "critical" = "info";
            if (rec.includes("🔴") || rec.includes("critical")) {
              type = "critical";
            } else if (
              rec.includes("🟠") ||
              rec.includes("⚠️") ||
              rec.includes("warning")
            ) {
              type = "warning";
            }
    
            return {
              type,
              title: "Documentation Freshness Insight",
              description: rec,
            };
          }) || [];
    
        const response: MCPToolResponse = {
          success: true,
          data: {
            summary: `Scanned ${report.totalFiles} files: ${report.criticalFiles} critical, ${report.staleFiles} stale, ${report.warningFiles} warnings, ${report.freshFiles} fresh`,
            report,
            thresholds: thresholds,
            formattedReport: enhancedReport,
            kgInsights,
          },
          metadata: {
            toolVersion: "1.0.0",
            executionTime: Date.now() - startTime,
            timestamp: new Date().toISOString(),
          },
          recommendations,
        };
    
        return response;
      } catch (error) {
        return {
          success: false,
          error: {
            code: "FRESHNESS_TRACKING_FAILED",
            message:
              error instanceof Error
                ? error.message
                : "Unknown error tracking documentation freshness",
            resolution: "Check that the documentation path exists and is readable",
          },
          metadata: {
            toolVersion: "1.0.0",
            executionTime: Date.now() - startTime,
            timestamp: new Date().toISOString(),
          },
        };
      }
    }
  • Zod input schema defining parameters for the tool, including paths, thresholds, presets, and output formatting options.
    export const TrackDocumentationFreshnessSchema = z.object({
      docsPath: z.string().describe("Path to documentation directory"),
      projectPath: z
        .string()
        .optional()
        .describe("Path to project root (for knowledge graph tracking)"),
      warningThreshold: z
        .object({
          value: z.number().positive(),
          unit: z.enum(["minutes", "hours", "days"]),
        })
        .optional()
        .describe("Warning threshold (yellow flag)"),
      staleThreshold: z
        .object({
          value: z.number().positive(),
          unit: z.enum(["minutes", "hours", "days"]),
        })
        .optional()
        .describe("Stale threshold (orange flag)"),
      criticalThreshold: z
        .object({
          value: z.number().positive(),
          unit: z.enum(["minutes", "hours", "days"]),
        })
        .optional()
        .describe("Critical threshold (red flag)"),
      preset: z
        .enum(["realtime", "active", "recent", "weekly", "monthly", "quarterly"])
        .optional()
        .describe("Use predefined threshold preset"),
      includeFileList: z
        .boolean()
        .optional()
        .default(true)
        .describe("Include detailed file list in response"),
      sortBy: z
        .enum(["age", "path", "staleness"])
        .optional()
        .default("staleness")
        .describe("Sort order for file list"),
      storeInKG: z
        .boolean()
        .optional()
        .default(true)
        .describe(
          "Store tracking event in knowledge graph for historical analysis",
        ),
    });
  • Helper function that formats the FreshnessScanReport into a human-readable Markdown report with statistics, freshness breakdown, recommendations, and detailed file lists sorted and grouped by staleness level.
    function formatFreshnessReport(
      report: FreshnessScanReport,
      includeFileList: boolean,
      sortBy: "age" | "path" | "staleness",
    ): string {
      const {
        totalFiles,
        filesWithMetadata,
        filesWithoutMetadata,
        freshFiles,
        warningFiles,
        staleFiles,
        criticalFiles,
        files,
        thresholds,
      } = report;
    
      let output = "# Documentation Freshness Report\n\n";
      output += `**Scanned at**: ${new Date(report.scannedAt).toLocaleString()}\n`;
      output += `**Documentation path**: ${report.docsPath}\n\n`;
    
      // Summary statistics
      output += "## Summary Statistics\n\n";
      output += `- **Total files**: ${totalFiles}\n`;
      output += `- **With metadata**: ${filesWithMetadata} (${Math.round(
        (filesWithMetadata / totalFiles) * 100,
      )}%)\n`;
      output += `- **Without metadata**: ${filesWithoutMetadata}\n\n`;
    
      // Freshness breakdown
      output += "## Freshness Breakdown\n\n";
      output += `- ✅ **Fresh**: ${freshFiles} files\n`;
      output += `- 🟡 **Warning**: ${warningFiles} files (older than ${thresholds.warning.value} ${thresholds.warning.unit})\n`;
      output += `- 🟠 **Stale**: ${staleFiles} files (older than ${thresholds.stale.value} ${thresholds.stale.unit})\n`;
      output += `- 🔴 **Critical**: ${criticalFiles} files (older than ${thresholds.critical.value} ${thresholds.critical.unit})\n`;
      output += `- ❓ **Unknown**: ${filesWithoutMetadata} files (no metadata)\n\n`;
    
      // Recommendations
      if (filesWithoutMetadata > 0 || criticalFiles > 0 || staleFiles > 0) {
        output += "## Recommendations\n\n";
    
        if (filesWithoutMetadata > 0) {
          output += `⚠️ **${filesWithoutMetadata} files lack freshness metadata**. Run \`validate_documentation_freshness\` to initialize metadata.\n\n`;
        }
    
        if (criticalFiles > 0) {
          output += `🔴 **${criticalFiles} files are critically stale**. Immediate review and update recommended.\n\n`;
        } else if (staleFiles > 0) {
          output += `🟠 **${staleFiles} files are stale**. Consider reviewing and updating soon.\n\n`;
        }
      }
    
      // File list
      if (includeFileList && files.length > 0) {
        output += "## File Details\n\n";
    
        // Sort files
        const sortedFiles = [...files];
        switch (sortBy) {
          case "age":
            sortedFiles.sort((a, b) => (b.ageInMs || 0) - (a.ageInMs || 0));
            break;
          case "path":
            sortedFiles.sort((a, b) =>
              a.relativePath.localeCompare(b.relativePath),
            );
            break;
          case "staleness": {
            const order = {
              critical: 0,
              stale: 1,
              warning: 2,
              fresh: 3,
              unknown: 4,
            };
            sortedFiles.sort(
              (a, b) => order[a.stalenessLevel] - order[b.stalenessLevel],
            );
            break;
          }
        }
    
        // Group by staleness level
        const grouped = {
          critical: sortedFiles.filter((f) => f.stalenessLevel === "critical"),
          stale: sortedFiles.filter((f) => f.stalenessLevel === "stale"),
          warning: sortedFiles.filter((f) => f.stalenessLevel === "warning"),
          fresh: sortedFiles.filter((f) => f.stalenessLevel === "fresh"),
          unknown: sortedFiles.filter((f) => f.stalenessLevel === "unknown"),
        };
    
        for (const [level, levelFiles] of Object.entries(grouped)) {
          if (levelFiles.length === 0) continue;
    
          const icon = {
            critical: "🔴",
            stale: "🟠",
            warning: "🟡",
            fresh: "✅",
            unknown: "❓",
          }[level];
    
          output += `### ${icon} ${
            level.charAt(0).toUpperCase() + level.slice(1)
          } (${levelFiles.length})\n\n`;
    
          for (const file of levelFiles) {
            output += `- **${file.relativePath}**`;
    
            if (file.ageFormatted) {
              output += ` - Last updated ${file.ageFormatted} ago`;
            }
    
            if (file.metadata?.validated_against_commit) {
              output += ` (commit: ${file.metadata.validated_against_commit.substring(
                0,
                7,
              )})`;
            }
    
            if (!file.hasMetadata) {
              output += " - ⚠️ No metadata";
            }
    
            output += "\n";
          }
    
          output += "\n";
        }
      }
    
      return output;
    }
  • Core helper that scans the documentation directory for markdown files, parses freshness metadata from frontmatter, calculates staleness levels based on thresholds, and generates a comprehensive FreshnessScanReport used by the handler.
    export async function scanDocumentationFreshness(
      docsPath: string,
      thresholds: {
        warning?: StalenessThreshold;
        stale?: StalenessThreshold;
        critical?: StalenessThreshold;
      } = {},
    ): Promise<FreshnessScanReport> {
      // Default thresholds
      const finalThresholds = {
        warning: thresholds.warning || STALENESS_PRESETS.weekly,
        stale: thresholds.stale || STALENESS_PRESETS.monthly,
        critical: thresholds.critical || STALENESS_PRESETS.quarterly,
      };
    
      // Find all markdown files
      const markdownFiles = await findMarkdownFiles(docsPath);
    
      // Analyze each file
      const files: FileFreshnessStatus[] = [];
      for (const filePath of markdownFiles) {
        const relativePath = path.relative(docsPath, filePath);
        const frontmatter = await parseDocFrontmatter(filePath);
        const status = calculateFreshnessStatus(
          filePath,
          relativePath,
          frontmatter,
          finalThresholds,
        );
        files.push(status);
      }
    
      // Calculate summary statistics
      const totalFiles = files.length;
      const filesWithMetadata = files.filter((f) => f.hasMetadata).length;
      const filesWithoutMetadata = totalFiles - filesWithMetadata;
      const freshFiles = files.filter((f) => f.stalenessLevel === "fresh").length;
      const warningFiles = files.filter(
        (f) => f.stalenessLevel === "warning",
      ).length;
      const staleFiles = files.filter((f) => f.stalenessLevel === "stale").length;
      const criticalFiles = files.filter(
        (f) => f.stalenessLevel === "critical",
      ).length;
    
      return {
        scannedAt: new Date().toISOString(),
        docsPath,
        totalFiles,
        filesWithMetadata,
        filesWithoutMetadata,
        freshFiles,
        warningFiles,
        staleFiles,
        criticalFiles,
        files,
        thresholds: finalThresholds,
      };
    }
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 scanning and identifying files, but doesn't describe what happens during execution (e.g., whether it modifies files, requires specific permissions, has rate limits, or what the output format looks like). For a tool with 9 parameters and no annotations, this leaves significant behavioral gaps.

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 functionality. Every word earns its place, with no redundant information or unnecessary elaboration, making it easy to parse quickly.

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 (9 parameters, nested objects, no output schema, and no annotations), the description is insufficient. It doesn't explain what the tool returns, how results are structured, or behavioral aspects like whether it's read-only or has side effects. For a tool with this level of complexity, more context is needed.

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 the schema already documents all parameters thoroughly. The description mentions 'configurable time thresholds (minutes, hours, days)', which aligns with the threshold parameters in the schema but doesn't add meaningful semantics beyond what's already in the schema descriptions. Baseline 3 is appropriate when schema does the heavy lifting.

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 tool's purpose: scanning a documentation directory for staleness markers and identifying files needing updates based on configurable time thresholds. It uses specific verbs ('scan', 'identify') and mentions the resource ('documentation directory'), but doesn't explicitly differentiate from sibling tools like 'validate_documentation_freshness' or 'detect_documentation_gaps'.

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 sibling tools or contexts where this tool is preferred over others like 'validate_documentation_freshness' or 'detect_documentation_gaps', leaving the agent with no usage context.

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/tosin2013/documcp'

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