Skip to main content
Glama

Get Vault Stats

get_vault_stats
Read-onlyIdempotent

Retrieves a vault health snapshot including note count, total bytes and words, unique tags, untagged notes, and most-recently-modified note to quickly assess vault condition.

Instructions

Return a quick health snapshot of the vault: note count, total bytes, total words, unique tag count, untagged-note count, and the most-recently-modified note. Useful for dashboards and 'is this vault healthy?' checks. Reads through the mtime cache so repeat calls are cheap.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
folderNoRestrict stats to this folder (relative to vault root). Omit for whole-vault stats.

Implementation Reference

  • The handler function for the 'get_vault_stats' tool. Lists notes in the vault (optionally filtered by folder), reads their content via mtime cache, computes total bytes, total words, unique tag count, untagged note count, and most-recently-modified note via fs.stat, then returns a formatted text snapshot.
    server.registerTool(
      "get_vault_stats",
      {
        title: "Get Vault Stats",
        description:
          "Return a quick health snapshot of the vault: note count, total bytes, total words, unique tag count, untagged-note count, and the most-recently-modified note. Useful for dashboards and 'is this vault healthy?' checks. Reads through the mtime cache so repeat calls are cheap.",
        annotations: {
          readOnlyHint: true,
          idempotentHint: true,
          openWorldHint: false,
        },
        inputSchema: {
          folder: z
            .string()
            .optional()
            .describe("Restrict stats to this folder (relative to vault root). Omit for whole-vault stats."),
        },
      },
      async ({ folder }) => {
        try {
          const notes = await listNotes(vaultPath, folder);
          if (notes.length === 0) {
            return { content: [{ type: "text" as const, text: folder ? `No notes in "${folder}"` : "Vault is empty." }] };
          }
          const { contents } = await readAllCached(vaultPath, notes, (note, err) => {
            log.warn("get_vault_stats: note read failed", { note, err });
          });
    
          let totalBytes = 0;
          let totalWords = 0;
          let untagged = 0;
          const tagSet = new Set<string>();
          for (const notePath of notes) {
            const content = contents.get(notePath);
            if (content === undefined) continue;
            totalBytes += Buffer.byteLength(content, "utf-8");
            // Word count: parse frontmatter out so YAML keys don't inflate
            // the count, then split body on whitespace.
            const { content: body } = parseFrontmatter(content);
            const matches = body.match(/\S+/g);
            totalWords += matches ? matches.length : 0;
            const tags = extractTags(content);
            if (tags.length === 0) untagged++;
            for (const t of tags) tagSet.add(t.toLowerCase());
          }
    
          // Most recent note via fs.stat — keep this independent of the cache
          // so it's accurate even if the cache hasn't been touched yet.
          let mostRecent: { path: string; mtimeMs: number } | null = null;
          const stats = await mapConcurrent<string, { path: string; mtimeMs: number } | undefined>(
            notes,
            16,
            async (notePath) => {
              try {
                const st = await getNoteStats(vaultPath, notePath);
                if (!st.modified) return undefined;
                return { path: notePath, mtimeMs: st.modified.getTime() };
              } catch {
                return undefined;
              }
            },
          );
          for (const s of stats) {
            if (!s) continue;
            if (!mostRecent || s.mtimeMs > mostRecent.mtimeMs) mostRecent = s;
          }
    
          const avgBytes = Math.round(totalBytes / notes.length);
          const avgWords = Math.round(totalWords / notes.length);
          const untaggedPct = ((untagged / notes.length) * 100).toFixed(1);
          const lines = [
            `Vault stats${folder ? ` (folder: ${folder})` : ""}`,
            "",
            `  Notes:           ${notes.length}`,
            `  Total bytes:     ${totalBytes.toLocaleString()}`,
            `  Total words:     ${totalWords.toLocaleString()}`,
            `  Avg bytes/note:  ${avgBytes.toLocaleString()}`,
            `  Avg words/note:  ${avgWords.toLocaleString()}`,
            `  Unique tags:     ${tagSet.size}`,
            `  Untagged notes:  ${untagged} (${untaggedPct}%)`,
            mostRecent
              ? `  Most recent:     ${mostRecent.path} (${new Date(mostRecent.mtimeMs).toISOString()})`
              : `  Most recent:     (none)`,
          ];
          return { content: [{ type: "text" as const, text: lines.join("\n") }] };
        } catch (err) {
          log.error("get_vault_stats failed", { tool: "get_vault_stats", err: err as Error });
          return errorResult(`Error gathering vault stats: ${sanitizeError(err)}`);
        }
      },
    );
  • Input schema for 'get_vault_stats'. Accepts an optional 'folder' string to restrict stats to a subfolder of the vault. Uses Zod validation with a description.
    {
      title: "Get Vault Stats",
      description:
        "Return a quick health snapshot of the vault: note count, total bytes, total words, unique tag count, untagged-note count, and the most-recently-modified note. Useful for dashboards and 'is this vault healthy?' checks. Reads through the mtime cache so repeat calls are cheap.",
      annotations: {
        readOnlyHint: true,
        idempotentHint: true,
        openWorldHint: false,
      },
      inputSchema: {
        folder: z
          .string()
          .optional()
          .describe("Restrict stats to this folder (relative to vault root). Omit for whole-vault stats."),
      },
  • Registration of 'get_vault_stats' tool with the MCP server via server.registerTool() inside the registerReadTools function (defined at line 15).
    server.registerTool(
      "get_vault_stats",
      {
        title: "Get Vault Stats",
        description:
          "Return a quick health snapshot of the vault: note count, total bytes, total words, unique tag count, untagged-note count, and the most-recently-modified note. Useful for dashboards and 'is this vault healthy?' checks. Reads through the mtime cache so repeat calls are cheap.",
        annotations: {
          readOnlyHint: true,
          idempotentHint: true,
          openWorldHint: false,
        },
        inputSchema: {
          folder: z
            .string()
            .optional()
            .describe("Restrict stats to this folder (relative to vault root). Omit for whole-vault stats."),
        },
      },
      async ({ folder }) => {
        try {
          const notes = await listNotes(vaultPath, folder);
          if (notes.length === 0) {
            return { content: [{ type: "text" as const, text: folder ? `No notes in "${folder}"` : "Vault is empty." }] };
          }
          const { contents } = await readAllCached(vaultPath, notes, (note, err) => {
            log.warn("get_vault_stats: note read failed", { note, err });
          });
    
          let totalBytes = 0;
          let totalWords = 0;
          let untagged = 0;
          const tagSet = new Set<string>();
          for (const notePath of notes) {
            const content = contents.get(notePath);
            if (content === undefined) continue;
            totalBytes += Buffer.byteLength(content, "utf-8");
            // Word count: parse frontmatter out so YAML keys don't inflate
            // the count, then split body on whitespace.
            const { content: body } = parseFrontmatter(content);
            const matches = body.match(/\S+/g);
            totalWords += matches ? matches.length : 0;
            const tags = extractTags(content);
            if (tags.length === 0) untagged++;
            for (const t of tags) tagSet.add(t.toLowerCase());
          }
    
          // Most recent note via fs.stat — keep this independent of the cache
          // so it's accurate even if the cache hasn't been touched yet.
          let mostRecent: { path: string; mtimeMs: number } | null = null;
          const stats = await mapConcurrent<string, { path: string; mtimeMs: number } | undefined>(
            notes,
            16,
            async (notePath) => {
              try {
                const st = await getNoteStats(vaultPath, notePath);
                if (!st.modified) return undefined;
                return { path: notePath, mtimeMs: st.modified.getTime() };
              } catch {
                return undefined;
              }
            },
          );
          for (const s of stats) {
            if (!s) continue;
            if (!mostRecent || s.mtimeMs > mostRecent.mtimeMs) mostRecent = s;
          }
    
          const avgBytes = Math.round(totalBytes / notes.length);
          const avgWords = Math.round(totalWords / notes.length);
          const untaggedPct = ((untagged / notes.length) * 100).toFixed(1);
          const lines = [
            `Vault stats${folder ? ` (folder: ${folder})` : ""}`,
            "",
            `  Notes:           ${notes.length}`,
            `  Total bytes:     ${totalBytes.toLocaleString()}`,
            `  Total words:     ${totalWords.toLocaleString()}`,
            `  Avg bytes/note:  ${avgBytes.toLocaleString()}`,
            `  Avg words/note:  ${avgWords.toLocaleString()}`,
            `  Unique tags:     ${tagSet.size}`,
            `  Untagged notes:  ${untagged} (${untaggedPct}%)`,
            mostRecent
              ? `  Most recent:     ${mostRecent.path} (${new Date(mostRecent.mtimeMs).toISOString()})`
              : `  Most recent:     (none)`,
          ];
          return { content: [{ type: "text" as const, text: lines.join("\n") }] };
        } catch (err) {
          log.error("get_vault_stats failed", { tool: "get_vault_stats", err: err as Error });
          return errorResult(`Error gathering vault stats: ${sanitizeError(err)}`);
        }
      },
    );
  • readAllCached helper: reads note contents with mtime-based caching. Used by the handler to efficiently retrieve note bodies for word counting and tag extraction.
    export async function readAllCached(
      vaultPath: string,
      relPaths: readonly string[],
      onError?: (relPath: string, err: Error) => void,
    ): Promise<ReadAllResult> {
      const state = stateFor(vaultPath);
      await loadFromDisk(vaultPath, state);
      const cache = state.entries;
      const seen = new Set<string>();
      const contents = new Map<string, string>();
      let cacheHits = 0;
      let cacheMisses = 0;
    
      await mapConcurrent(relPaths, READ_CONCURRENCY, async (relPath) => {
        seen.add(relPath);
        let fullPath: string;
        try {
          fullPath = await resolveVaultPathSafe(vaultPath, relPath);
        } catch (err) {
          onError?.(relPath, err as Error);
          return undefined;
        }
        let mtimeMs: number;
        try {
          const stat = await fs.stat(fullPath);
          mtimeMs = stat.mtimeMs;
        } catch (err) {
          // ENOENT during stat means the file disappeared between listing and
          // reading — drop the cache entry and skip.
          if (cache.delete(relPath)) state.dirty = true;
          onError?.(relPath, err as Error);
          return undefined;
        }
        const cached = cache.get(relPath);
        if (cached && cached.mtimeMs === mtimeMs && cached.fullPath === fullPath) {
          contents.set(relPath, cached.content);
          cacheHits++;
          return undefined;
        }
        let content: string;
        try {
          content = await fs.readFile(fullPath, "utf-8");
        } catch (err) {
          onError?.(relPath, err as Error);
          if (cache.delete(relPath)) state.dirty = true;
          return undefined;
        }
        cache.set(relPath, { fullPath, relPath, content, mtimeMs });
        state.dirty = true;
        contents.set(relPath, content);
        cacheMisses++;
        return undefined;
      });
    
      // Prune entries that weren't asked for this round. This stops the cache
      // from holding stale paths after a vault reorg or folder filter change.
      for (const key of cache.keys()) {
        if (!seen.has(key)) {
          cache.delete(key);
          state.dirty = true;
        }
      }
    
      if (state.dirty) scheduleFlush(vaultPath, state);
    
      return { contents, cacheHits, cacheMisses };
    }
  • getNoteStats helper: returns file stats (size, created, modified) via fs.stat. Used by the handler to find the most recently modified note.
    export async function getNoteStats(
      vaultPath: string,
      relativePath: string,
    ): Promise<{ size: number; created: Date | null; modified: Date | null }> {
      const fullPath = await resolveVaultPathSafe(vaultPath, relativePath);
      const stats = await fs.stat(fullPath);
    
      return {
        size: stats.size,
        created: stats.birthtime ?? null,
        modified: stats.mtime ?? null,
      };
    }
Behavior5/5

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

Annotations already indicate read-only and idempotent behavior. The description adds valuable transparency by noting it 'reads through the mtime cache so repeat calls are cheap', which exceeds annotation coverage and helps the agent understand performance implications.

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 extremely concise—two sentences that immediately list outputs and use case. No wasted words, and every sentence adds value.

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's simplicity (1 optional parameter, no output schema), the description fully covers the return values and adds performance context. It is complete for the tool's complexity.

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 coverage is 100% and the schema already describes the 'folder' parameter clearly. The description does not add new semantic information beyond what is in the schema, so a baseline score of 3 is appropriate.

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 uses a specific verb 'Return' and enumerates the exact metrics (note count, bytes, words, etc.), clearly distinguishing this aggregation tool from sibling tools that operate on individual notes or tags.

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 states it is 'useful for dashboards and 'is this vault healthy?' checks', providing clear usage context. It lacks explicit when-not-to-use or alternatives, but the intended use case is well-communicated.

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/rps321321/obsidian-mcp-pro'

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