Skip to main content
Glama

verify_audit_chain

Recomputes the SHA-256 hash chain over your audit log to detect mutated, deleted, or reordered events. Use as a tamper-evidence check to verify integrity.

Instructions

[audit] Recompute the SHA-256 hash chain over the audit log and confirm no event has been mutated, deleted, or reordered. Use periodically as a tamper-evidence check, or whenever you suspect the audit log has been touched outside q-ring; the result is informational — this tool does not repair the chain if it is broken. Read-only. Returns JSON { ok, valid, brokenAt? } where valid is true for an intact chain and brokenAt (when present) names the first event whose hash did not match.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • Core handler: Recomputes SHA-256 hash chain over the audit log file (audit.jsonl) and verifies each event's prevHash matches the hash of the previous event. Returns VerifyResult with totalEvents, validEvents, brokenAt index, brokenEvent, and intact flag.
    /**
     * Verify the hash-chain integrity of the entire audit log.
     * Returns the first break point if the chain has been tampered with.
     */
    export function verifyAuditChain(): VerifyResult {
      const path = getAuditPath();
      if (!existsSync(path)) {
        return { totalEvents: 0, validEvents: 0, intact: true };
      }
    
      const lines = readFileSync(path, "utf8")
        .split("\n")
        .filter((l) => l.trim());
    
      if (lines.length === 0) {
        return { totalEvents: 0, validEvents: 0, intact: true };
      }
    
      let validEvents = 0;
    
      for (let i = 0; i < lines.length; i++) {
        let event: AuditEvent;
        try {
          event = JSON.parse(lines[i]);
        } catch {
          return {
            totalEvents: lines.length,
            validEvents,
            brokenAt: i,
            intact: false,
          };
        }
    
        if (i === 0) {
          validEvents++;
          continue;
        }
    
        const expectedHash = createHash("sha256")
          .update(lines[i - 1])
          .digest("hex");
    
        if (event.prevHash !== expectedHash) {
          return {
            totalEvents: lines.length,
            validEvents,
            brokenAt: i,
            brokenEvent: event,
            intact: false,
          };
        }
    
        validEvents++;
      }
    
      return { totalEvents: lines.length, validEvents, intact: true };
    }
  • VerifyResult interface: Return type for verifyAuditChain() containing totalEvents, validEvents, optional brokenAt index, optional brokenEvent, and intact boolean.
    export interface VerifyResult {
      totalEvents: number;
      validEvents: number;
      brokenAt?: number;
      brokenEvent?: AuditEvent;
      intact: boolean;
    }
  • MCP tool registration: Registers 'verify_audit_chain' as a read-only MCP tool with description, empty schema params, and async handler that calls verifyAuditChain() and returns JSON result.
    server.tool(
      "verify_audit_chain",
      [
        "[audit] Recompute the SHA-256 hash chain over the audit log and confirm no event has been mutated, deleted, or reordered.",
        "Use periodically as a tamper-evidence check, or whenever you suspect the audit log has been touched outside q-ring; the result is informational — this tool does not repair the chain if it is broken.",
        "Read-only. Returns JSON `{ ok, valid, brokenAt? }` where `valid` is `true` for an intact chain and `brokenAt` (when present) names the first event whose hash did not match.",
      ].join(" "),
      {},
      async () => {
        const toolBlock = enforceToolPolicy("verify_audit_chain");
        if (toolBlock) return toolBlock;
    
        const result = verifyAuditChain();
        return text(JSON.stringify(result, null, 2));
      },
    );
  • CLI command registration: Registers 'audit:verify' commander command that calls verifyAuditChain() and displays result with color-coded success/failure output.
    program
      .command("audit:verify")
      .description("Verify the integrity of the audit hash chain")
      .action(() => {
        const result = verifyAuditChain();
        if (result.totalEvents === 0) {
          console.log(c.dim("  No audit events to verify"));
          return;
        }
    
        if (result.intact) {
          console.log(
            `${SYMBOLS.shield} ${c.green("Audit chain intact")} — ${result.totalEvents} events verified`,
          );
        } else {
          console.log(
            `${SYMBOLS.cross} ${c.red("Audit chain BROKEN")} at event #${result.brokenAt}`,
          );
          console.log(
            c.dim(
              `  ${result.validEvents}/${result.totalEvents} events valid before break`,
            ),
          );
          if (result.brokenEvent) {
            console.log(
              c.dim(
                `  Broken event: ${result.brokenEvent.timestamp} ${result.brokenEvent.action} ${result.brokenEvent.key ?? ""}`,
              ),
            );
          }
          process.exitCode = 1;
        }
      });
  • Helper functions: getAuditDir() resolves audit directory (from QRING_AUDIT_DIR env var or ~/.config/q-ring), getAuditPath() returns full path to audit.jsonl.
    function getAuditDir(): string {
      if (process.env.QRING_AUDIT_DIR) {
        if (!existsSync(process.env.QRING_AUDIT_DIR)) {
          mkdirSync(process.env.QRING_AUDIT_DIR, { recursive: true });
        }
        return process.env.QRING_AUDIT_DIR;
      }
      const dir = join(homedir(), ".config", "q-ring");
      if (!existsSync(dir)) {
        mkdirSync(dir, { recursive: true });
      }
      return dir;
    }
    
    function getAuditPath(): string {
      return join(getAuditDir(), "audit.jsonl");
    }
Behavior5/5

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

With no annotations, the description fully carries the burden. It explicitly states the tool is read-only, does not repair the chain, and describes the return format (JSON with fields ok, valid, brokenAt). This provides clear expected behavior beyond the empty input schema.

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 concise (two sentences with a tag) and front-loaded with purpose. Every sentence adds value: purpose, usage guidance, behavioral info, and return format. No redundancy or wordiness.

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

Completeness5/5

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

Given the tool is simple (0 parameters, no output schema), the description covers purpose, usage, behavior, return structure, and limitations. It is fully adequate for an agent to select and invoke the tool correctly.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The tool has zero parameters and schema coverage is 100% (empty object). No parameter description is needed. The description correctly omits parameter details, meeting the baseline for zero-parameter tools.

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 it recomputes the SHA-256 hash chain over the audit log and confirms no event has been mutated, deleted, or reordered. The verb 'recompute' and resource 'audit log' are specific. It distinguishes from siblings like 'audit_log' by focusing on tamper-evidence verification.

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 advises using it 'periodically as a tamper-evidence check' or when suspecting unauthorized changes. It also notes the result is informational and does not repair. However, it does not explicitly exclude situations or mention alternatives, leaving minor gaps.

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/I4cTime/quantum_ring'

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