Skip to main content
Glama

memory_stats

Retrieve memory system statistics: counts by category and project, most accessed items, and recent searches.

Instructions

Show memory system statistics — counts by category, project, most accessed, and recent searches.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The handler function `handleMemoryStats()` that executes the memory_stats tool logic. It queries the SQLite database for counts of memories, journal entries, archives, searches, and presents them grouped by category, project, most accessed, and recent searches.
    export async function handleMemoryStats(): Promise<string> {
      const db = getDb();
    
      const memCount = (db.prepare(`SELECT COUNT(*) as c FROM memories`).get() as { c: number }).c;
      const journalCount = (db.prepare(`SELECT COUNT(*) as c FROM journal_entries`).get() as { c: number }).c;
      const archivedCount = (db.prepare(`SELECT COUNT(*) as c FROM memories WHERE archived = 1`).get() as { c: number }).c;
      const searchCount = (db.prepare(`SELECT COUNT(*) as c FROM search_log`).get() as { c: number }).c;
    
      const byCategory = db
        .prepare(`SELECT category, COUNT(*) as c FROM memories WHERE archived = 0 GROUP BY category ORDER BY c DESC`)
        .all() as Array<{ category: string; c: number }>;
    
      const byProject = db
        .prepare(
          `SELECT COALESCE(project, '(no project)') as project, COUNT(*) as c FROM memories WHERE archived = 0 GROUP BY project ORDER BY c DESC LIMIT 10`,
        )
        .all() as Array<{ project: string; c: number }>;
    
      const topAccessed = db
        .prepare(`SELECT content, access_count, category FROM memories WHERE access_count > 0 ORDER BY access_count DESC LIMIT 5`)
        .all() as Array<{ content: string; access_count: number; category: string }>;
    
      const recentSearches = db
        .prepare(`SELECT query, results_count, created_at FROM search_log ORDER BY created_at DESC LIMIT 5`)
        .all() as Array<{ query: string; results_count: number; created_at: number }>;
    
      let output = `## Memory Stats\n\n`;
      output += `- **Memories**: ${memCount} active, ${archivedCount} archived\n`;
      output += `- **Journal entries**: ${journalCount}\n`;
      output += `- **Searches performed**: ${searchCount}\n`;
      output += `- **Search mode**: ${isUsingFallback() ? "keyword (Ollama not available)" : "semantic (Ollama)"}\n\n`;
    
      if (byCategory.length > 0) {
        output += `### By Category\n`;
        for (const { category, c } of byCategory) {
          output += `- ${category}: ${c}\n`;
        }
        output += "\n";
      }
    
      if (byProject.length > 0) {
        output += `### By Project\n`;
        for (const { project, c } of byProject) {
          output += `- ${project}: ${c}\n`;
        }
        output += "\n";
      }
    
      if (topAccessed.length > 0) {
        output += `### Most Accessed\n`;
        for (const { content, access_count, category } of topAccessed) {
          output += `- (${access_count}x, ${category}) ${content.slice(0, 80)}\n`;
        }
        output += "\n";
      }
    
      if (recentSearches.length > 0) {
        output += `### Recent Searches\n`;
        for (const { query, results_count, created_at } of recentSearches) {
          const date = new Date(created_at).toISOString().slice(0, 16).replace("T", " ");
          output += `- "${query}" → ${results_count} results (${date})\n`;
        }
      }
    
      return output;
    }
  • Registration of the 'memory_stats' tool on the MCP server via `server.tool()` with an empty schema (no inputs) and a callback that calls handleMemoryStats().
    server.tool(
      "memory_stats",
      "Show memory system statistics — counts by category, project, most accessed, and recent searches.",
      {},
      async () => {
        try {
          const result = await handleMemoryStats();
          return { content: [{ type: "text", text: result }] };
        } catch (err) {
          return {
            content: [{ type: "text", text: `Error getting stats: ${err}` }],
            isError: true,
          };
        }
      },
    );
  • The schema is an empty object '{}' — the memory_stats tool takes no input parameters.
    {},
  • Helper function `getDb()` that initializes and returns the SQLite database connection, used by the handler to run queries on the memories, journal_entries, and search_log tables.
    export function getDb(): any {
      if (_db) return _db;
      if (_unavailable || !Database) {
        _unavailable = true;
        throw new Error(
          "Memory database unavailable — better-sqlite3 failed to load. " +
          "This is usually a native compilation issue. Memory features are disabled but everything else works. " +
          "Try: npm rebuild better-sqlite3"
        );
      }
    
      try {
        fs.mkdirSync(DB_DIR, { recursive: true });
        _db = new Database(DB_PATH);
    
        _db.pragma("journal_mode = WAL");
    
        _db.exec(`
          CREATE TABLE IF NOT EXISTS memories (
            id TEXT PRIMARY KEY,
            content TEXT NOT NULL,
            category TEXT NOT NULL DEFAULT 'general',
            project TEXT,
            source_file TEXT,
            created_at INTEGER NOT NULL,
            updated_at INTEGER NOT NULL,
            accessed_at INTEGER NOT NULL,
            access_count INTEGER NOT NULL DEFAULT 0,
            archived INTEGER NOT NULL DEFAULT 0,
            embedding BLOB
          );
    
          CREATE TABLE IF NOT EXISTS journal_entries (
            id TEXT PRIMARY KEY,
            session_id TEXT,
            project TEXT,
            content TEXT NOT NULL,
            created_at INTEGER NOT NULL,
            embedding BLOB
          );
    
          CREATE TABLE IF NOT EXISTS search_log (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            query TEXT NOT NULL,
            results_count INTEGER NOT NULL,
            created_at INTEGER NOT NULL
          );
    
          CREATE INDEX IF NOT EXISTS idx_memories_category ON memories(category);
          CREATE INDEX IF NOT EXISTS idx_memories_project ON memories(project);
          CREATE INDEX IF NOT EXISTS idx_memories_created ON memories(created_at);
          CREATE INDEX IF NOT EXISTS idx_memories_archived ON memories(archived);
          CREATE INDEX IF NOT EXISTS idx_journal_created ON journal_entries(created_at);
          CREATE INDEX IF NOT EXISTS idx_journal_project ON journal_entries(project);
        `);
    
        return _db;
      } catch (err) {
        _unavailable = true;
        throw new Error(`Memory database failed to initialize: ${err}`);
      }
    }
  • Helper function `isUsingFallback()` that returns whether Ollama is unavailable (fallback to keyword search), used in the handler output to indicate the search mode.
    export function isUsingFallback(): boolean {
      return _fallbackMode === true;
    }
Behavior2/5

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

No annotations provided, so description carries full burden. It describes output content but does not mention any behavioral traits (e.g., read-only, side effects, data staleness). Minimal transparency.

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?

Single efficient sentence, front-loaded with verb and resource. No fluff.

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?

For a zero-parameter, no-output-schema tool, description adequately conveys purpose and output. Could benefit from explicit read-only hint, but not critical.

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?

No parameters; schema coverage is 100%. Description correctly omits parameter info. Baseline 4 applies as no param info needed.

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?

Description clearly states verb ('Show') and resource ('memory system statistics'), and lists specific categories (counts by category, project, most accessed, recent searches). This distinguishes it from siblings like memory_search (queries) and memory_recent (list recent entries).

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

Usage Guidelines3/5

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

Implies use when needing aggregate statistics, but no explicit when-not-to-use or alternative tool references. Sibling names provide context but description itself lacks guidance.

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/DomDemetz/claude-soul'

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