Skip to main content
Glama

validate_documentation_freshness

Check documentation freshness by validating timestamps against code changes, initializing metadata for new files, and updating validation records.

Instructions

Validate documentation freshness, initialize metadata for files without it, and update timestamps based on code changes

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
docsPathYesPath to documentation directory
projectPathYesPath to project root (for git integration)
initializeMissingNoInitialize metadata for files without it
updateExistingNoUpdate last_validated timestamp for all files
updateFrequencyNoDefault update frequency for new metadatamonthly
validateAgainstGitNoValidate against current git commit

Implementation Reference

  • The core handler function that performs documentation freshness validation. It processes markdown files in the docs path, initializes missing freshness metadata, optionally updates existing metadata, integrates with git for commit tracking, generates a formatted report, and stores the validation event in the knowledge graph.
    export async function validateDocumentationFreshness(
      input: ValidateDocumentationFreshnessInput,
    ): Promise<MCPToolResponse> {
      const startTime = Date.now();
    
      try {
        const {
          docsPath,
          projectPath,
          initializeMissing,
          updateExisting,
          updateFrequency,
          validateAgainstGit,
        } = input;
    
        // Get current git commit if requested
        let currentCommit: string | undefined;
        if (validateAgainstGit) {
          try {
            const git = simpleGit(projectPath);
            const isRepo = await git.checkIsRepo();
    
            if (isRepo) {
              const log = await git.log({ maxCount: 1 });
              currentCommit = log.latest?.hash;
            }
          } catch (error) {
            // Git not available, continue without it
          }
        }
    
        // Find all markdown files
        const markdownFiles = await findMarkdownFiles(docsPath);
        const results: FileValidationResult[] = [];
    
        for (const filePath of markdownFiles) {
          const relativePath = path.relative(docsPath, filePath);
    
          try {
            const frontmatter = await parseDocFrontmatter(filePath);
            const hasMetadata = !!frontmatter.documcp?.last_updated;
    
            if (!hasMetadata && initializeMissing) {
              // Initialize metadata
              await initializeFreshnessMetadata(filePath, {
                updateFrequency,
                autoUpdated: false,
              });
    
              // If git is available, set validated_against_commit
              if (currentCommit) {
                await updateDocFrontmatter(filePath, {
                  validated_against_commit: currentCommit,
                });
              }
    
              const updatedFrontmatter = await parseDocFrontmatter(filePath);
              results.push({
                filePath,
                relativePath,
                action: "initialized",
                metadata: updatedFrontmatter.documcp,
              });
            } else if (hasMetadata && updateExisting) {
              // Update existing metadata
              const updateData: Partial<DocFreshnessMetadata> = {
                last_validated: new Date().toISOString(),
              };
    
              if (currentCommit) {
                updateData.validated_against_commit = currentCommit;
              }
    
              await updateDocFrontmatter(filePath, updateData);
    
              const updatedFrontmatter = await parseDocFrontmatter(filePath);
              results.push({
                filePath,
                relativePath,
                action: "updated",
                metadata: updatedFrontmatter.documcp,
              });
            } else {
              results.push({
                filePath,
                relativePath,
                action: "skipped",
                metadata: frontmatter.documcp,
              });
            }
          } catch (error) {
            results.push({
              filePath,
              relativePath,
              action: "error",
              error: error instanceof Error ? error.message : "Unknown error",
            });
          }
        }
    
        // Generate report
        const report: ValidationReport = {
          validatedAt: new Date().toISOString(),
          docsPath,
          projectPath,
          totalFiles: markdownFiles.length,
          initialized: results.filter((r) => r.action === "initialized").length,
          updated: results.filter((r) => r.action === "updated").length,
          skipped: results.filter((r) => r.action === "skipped").length,
          errors: results.filter((r) => r.action === "error").length,
          currentCommit,
          files: results,
        };
    
        const formattedReport = formatValidationReport(report);
    
        // Store validation event in knowledge graph
        let eventId: string | undefined;
        if (report.initialized > 0 || report.updated > 0) {
          try {
            // Scan current state to get freshness metrics
            const scanReport = await scanDocumentationFreshness(docsPath, {
              warning: STALENESS_PRESETS.monthly,
              stale: {
                value: STALENESS_PRESETS.monthly.value * 2,
                unit: STALENESS_PRESETS.monthly.unit,
              },
              critical: {
                value: STALENESS_PRESETS.monthly.value * 3,
                unit: STALENESS_PRESETS.monthly.unit,
              },
            });
    
            // Determine event type
            const eventType = report.initialized > 0 ? "initialization" : "update";
    
            // Store in KG
            eventId = await storeFreshnessEvent(
              projectPath,
              docsPath,
              scanReport,
              eventType,
            );
    
            // Update event with validation details
            await updateFreshnessEvent(eventId, {
              filesInitialized: report.initialized,
              filesUpdated: report.updated,
              eventType,
            });
          } catch (error) {
            // KG storage failed, but continue with the response
            console.warn(
              "Failed to store validation event in knowledge graph:",
              error,
            );
          }
        }
    
        const response: MCPToolResponse = {
          success: true,
          data: {
            summary: `Validated ${report.totalFiles} files: ${report.initialized} initialized, ${report.updated} updated`,
            report,
            formattedReport,
            kgEventId: eventId,
          },
          metadata: {
            toolVersion: "1.0.0",
            executionTime: Date.now() - startTime,
            timestamp: new Date().toISOString(),
          },
          recommendations: [],
        };
    
        return response;
      } catch (error) {
        return {
          success: false,
          error: {
            code: "FRESHNESS_VALIDATION_FAILED",
            message:
              error instanceof Error
                ? error.message
                : "Unknown error validating documentation freshness",
            resolution:
              "Check that the documentation and project paths exist and are readable",
          },
          metadata: {
            toolVersion: "1.0.0",
            executionTime: Date.now() - startTime,
            timestamp: new Date().toISOString(),
          },
        };
      }
    }
  • Zod schema defining the input parameters for the validate_documentation_freshness tool, including paths, flags for initialization/updating, frequency preset, and git validation option.
    export const ValidateDocumentationFreshnessSchema = z.object({
      docsPath: z.string().describe("Path to documentation directory"),
      projectPath: z
        .string()
        .describe("Path to project root (for git integration)"),
      initializeMissing: z
        .boolean()
        .optional()
        .default(true)
        .describe("Initialize metadata for files without it"),
      updateExisting: z
        .boolean()
        .optional()
        .default(false)
        .describe("Update last_validated timestamp for all files"),
      updateFrequency: z
        .enum(["realtime", "active", "recent", "weekly", "monthly", "quarterly"])
        .optional()
        .default("monthly")
        .describe("Default update frequency for new metadata"),
      validateAgainstGit: z
        .boolean()
        .optional()
        .default(true)
        .describe("Validate against current git commit"),
    });
  • Helper function that formats the validation results into a readable Markdown report with summary, actions performed, and next steps.
    function formatValidationReport(report: ValidationReport): string {
      let output = "# Documentation Freshness Validation Report\n\n";
      output += `**Validated at**: ${new Date(
        report.validatedAt,
      ).toLocaleString()}\n`;
      output += `**Documentation path**: ${report.docsPath}\n`;
    
      if (report.currentCommit) {
        output += `**Current commit**: ${report.currentCommit.substring(0, 7)}\n`;
      }
    
      output += "\n## Summary\n\n";
      output += `- **Total files**: ${report.totalFiles}\n`;
      output += `- **Initialized**: ${report.initialized} files\n`;
      output += `- **Updated**: ${report.updated} files\n`;
      output += `- **Skipped**: ${report.skipped} files\n`;
    
      if (report.errors > 0) {
        output += `- **Errors**: ${report.errors} files\n`;
      }
    
      output += "\n## Actions Performed\n\n";
    
      // Group by action
      const grouped = {
        initialized: report.files.filter((f) => f.action === "initialized"),
        updated: report.files.filter((f) => f.action === "updated"),
        error: report.files.filter((f) => f.action === "error"),
      };
    
      if (grouped.initialized.length > 0) {
        output += `### ✨ Initialized (${grouped.initialized.length})\n\n`;
        for (const file of grouped.initialized) {
          output += `- ${file.relativePath}\n`;
        }
        output += "\n";
      }
    
      if (grouped.updated.length > 0) {
        output += `### 🔄 Updated (${grouped.updated.length})\n\n`;
        for (const file of grouped.updated) {
          output += `- ${file.relativePath}\n`;
        }
        output += "\n";
      }
    
      if (grouped.error.length > 0) {
        output += `### ❌ Errors (${grouped.error.length})\n\n`;
        for (const file of grouped.error) {
          output += `- ${file.relativePath}: ${file.error}\n`;
        }
        output += "\n";
      }
    
      // Recommendations
      output += "## Next Steps\n\n";
    
      if (report.initialized > 0) {
        output += `→ ${report.initialized} files now have freshness tracking enabled\n`;
      }
    
      if (report.updated > 0) {
        output += `→ ${report.updated} files have been marked as validated\n`;
      }
    
      output += `→ Run \`track_documentation_freshness\` to view current freshness status\n`;
    
      return output;
    }
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 that the tool can 'initialize metadata for files without it' and 'update timestamps based on code changes', which implies mutation capabilities, but doesn't specify whether this requires specific permissions, what happens to existing metadata, whether changes are reversible, or any rate limits. For a tool with potential write operations and no annotations, this is insufficient.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that front-loads the core actions (validate, initialize, update). Every phrase earns its place by specifying distinct functionalities, though it could be slightly more structured (e.g., separating validation from initialization/update aspects).

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 (6 parameters, potential mutations, no annotations, no output schema), the description is incomplete. It doesn't explain what 'validate' entails (e.g., what criteria are used), what metadata is initialized/updated, or what the tool returns. For a tool with significant functionality and no structured support, more detail 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?

Schema description coverage is 100%, so the schema already documents all 6 parameters thoroughly. The description adds no additional parameter semantics beyond what's in the schema (e.g., it doesn't explain the relationship between 'initializeMissing' and 'updateExisting', or clarify what 'validateAgainstGit' entails). Baseline 3 is appropriate when the 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 with specific verbs ('validate', 'initialize', 'update') and resources ('documentation freshness', 'metadata', 'timestamps'). It distinguishes from some siblings like 'track_documentation_freshness' (which likely monitors rather than validates/updates) and 'validate_content' (which validates content rather than freshness), though the distinction could be more explicit.

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 when to prefer 'track_documentation_freshness' (a sibling tool) for monitoring versus this tool for validation/updates, or how it relates to 'validate_content' or 'detect_documentation_gaps'. Usage is implied but not explicitly stated.

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