Skip to main content
Glama

Memory File Statistics

memory_stats
Read-onlyIdempotent

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

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

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}"}
Behavior3/5

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

Annotations already declare readOnlyHint=true and idempotentHint=true, so the agent knows this is a safe, repeatable read operation. The description adds value by specifying the type of data returned ('detailed statistics and optimization status'), which isn't covered by annotations, but it doesn't disclose behavioral aspects like rate limits, authentication needs, or what happens if the memory_file parameter is null (default).

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 a single, efficient sentence that front-loads the core purpose ('Get detailed statistics and optimization status') without any unnecessary words. Every part of the sentence contributes directly to understanding the tool's function, making it highly concise and well-structured.

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?

Given the tool's low complexity (one optional parameter), rich annotations (readOnlyHint, idempotentHint), and the presence of an output schema (which handles return values), the description is reasonably complete. It specifies what data is retrieved, though it could benefit from more context on usage scenarios or parameter details to be fully comprehensive.

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 0%, so the schema provides no documentation for the 'memory_file' parameter. The description doesn't add any semantic details about this parameter, such as what a memory file is, how to identify it, or the implications of using null (default). However, with only one optional parameter, the baseline is higher, but the lack of compensation for the coverage gap keeps it at an adequate level.

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 action ('Get detailed statistics and optimization status') and resource ('for a memory file'), making the purpose immediately understandable. However, it doesn't differentiate this tool from potential sibling tools like 'optimize_memory' or 'browse_mode_library', which might also provide memory-related information, so it doesn't reach the highest score.

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. With sibling tools like 'optimize_memory' and 'browse_mode_library' available, there's no indication of whether this tool is for pre-optimization analysis, post-optimization verification, or general monitoring, leaving the agent to guess based on context.

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

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