Skip to main content
Glama

memory_stats

Retrieve detailed statistics and optimization status for memory files to monitor performance and identify improvement opportunities.

Instructions

Get detailed statistics and optimization status for a memory file.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
memory_fileNo

Implementation Reference

  • The handler function for the memory_stats tool. It resolves the memory file path, instantiates MemoryOptimizer, calls get_memory_stats, and formats the results into a user-friendly string message.
    def memory_stats(
        memory_file: Annotated[Optional[str], "Path to memory file to analyze"] = None,
    ) -> str:
        """Get detailed statistics about a memory file."""
        try:
            # Determine which file to analyze
            if memory_file:
                file_path = Path(memory_file)
                if not file_path.exists():
                    return f"Error: Memory file not found: {memory_file}"
            else:
                # Use default user memory file
                user_memory_path = instruction_manager.get_memory_file_path()
                if not user_memory_path.exists():
                    return "No user memory file found"
                file_path = user_memory_path
    
            # Get stats
            optimizer = MemoryOptimizer(instruction_manager)
            stats = optimizer.get_memory_stats(file_path)
    
            if "error" in stats:
                return str(stats["error"])
    
            # Format stats message
            message = f"📊 **Memory File Statistics**\n\n"
            message += f"📁 **File**: `{stats['file_path']}`\n"
            message += f"📏 **Size**: {stats['file_size_bytes']:,} bytes\n"
            message += f"📝 **Entries**: {stats['current_entries']}\n"
            message += f"🔄 **Last Optimized**: {stats['last_optimized'] or 'Never'}\n"
            message += f"⚡ **Optimization Version**: {stats['optimization_version']}\n\n"
    
            message += f"⚙️ **Configuration**:\n"
            message += f"• Auto-optimize: {'✅ Enabled' if stats['auto_optimize_enabled'] else '❌ Disabled'}\n"
            message += f"• Size threshold: {stats['size_threshold']:,} bytes\n"
            message += f"• Entry threshold: {stats['entry_threshold']} new entries\n"
            message += f"• Time threshold: {stats['time_threshold_days']} days\n\n"
    
            message += f"🎯 **Optimization Status**:\n"
            message += f"• Eligible: {'✅ Yes' if stats['optimization_eligible'] else '❌ No'}\n"
            message += f"• Reason: {stats['optimization_reason']}\n"
            message += f"• New entries since last optimization: {stats['entries_since_last_optimization']}"
    
            return message
    
        except Exception as e:
            return f"Error getting memory stats: {str(e)}"
  • Registers the memory_stats tool with the FastMCP app, including description, tags, input/output schema via annotations, and metadata.
    @app.tool(
        name="memory_stats",
        description="Get detailed statistics and optimization status for a memory file.",
        tags={"public", "memory"},
        annotations={
            "idempotentHint": True,
            "readOnlyHint": True,
            "title": "Memory File Statistics",
            "parameters": {
                "memory_file": "Optional path to specific memory file. If not provided, will show stats for the user's main memory file.",
            },
            "returns": "Returns comprehensive statistics including file size, entry count, optimization eligibility, and configuration settings.",
        },
        meta={
            "category": "memory",
        },
    )
  • Helper method in MemoryOptimizer class that computes the core statistics dictionary for a memory file, including file info, counts, metadata, and optimization eligibility. Called by the tool handler.
    def get_memory_stats(self, file_path: Path) -> Dict[str, Any]:
        """
        Get statistics about a memory file.
    
        Returns metadata and file information for user inspection.
        """
        try:
            metadata = self._get_memory_metadata(file_path)
            frontmatter, content = parse_frontmatter_file(file_path)
    
            current_entries = self._count_memory_entries(content)
            file_size = file_path.stat().st_size
    
            # Calculate optimization eligibility
            should_optimize, reason = self._should_optimize_memory(file_path, metadata)
    
            return {
                "file_path": str(file_path),
                "file_size_bytes": file_size,
                "current_entries": current_entries,
                "last_optimized": metadata.get("lastOptimized"),
                "optimization_version": metadata.get("optimizationVersion", 0),
                "auto_optimize_enabled": metadata.get("autoOptimize", True),
                "size_threshold": metadata.get("sizeThreshold", 50000),
                "entry_threshold": metadata.get("entryThreshold", 20),
                "time_threshold_days": metadata.get("timeThreshold", 7),
                "optimization_eligible": should_optimize,
                "optimization_reason": reason,
                "entries_since_last_optimization": current_entries - metadata.get("entryCount", 0),
            }
    
        except Exception as e:
            return {"error": f"Could not read memory file stats: {e}"}

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/NiclasOlofsson/mode-manager-mcp'

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