Skip to main content
Glama

analyze_storage

Read-only

Analyze disk usage on critical paths and examine pacman cache to identify and resolve storage issues.

Instructions

[MONITORING] Unified storage analysis tool. Actions: disk_usage (check disk space for critical paths), cache_stats (analyze pacman package cache). Works on any system for disk_usage, Arch only for cache_stats.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
actionYesAnalysis type to perform

Implementation Reference

  • The main handler function for the 'analyze_storage' tool. Dispatches to check_disk_space() or get_pacman_cache_stats() based on the action parameter ('disk_usage' or 'cache_stats'). Returns an error response for invalid actions.
    async def analyze_storage(action: str) -> Dict[str, Any]:
        """
        Unified storage analysis tool.
        
        Args:
            action: "disk_usage" or "cache_stats"
        
        Returns:
            Analysis results based on action
        """
        if action == "disk_usage":
            return await check_disk_space()
        elif action == "cache_stats":
            return await get_pacman_cache_stats()
        else:
            return create_error_response(
                "InvalidAction",
                f"Unknown action: {action}. Use 'disk_usage' or 'cache_stats'"
            )
  • Helper: check_disk_space() - Checks disk usage for critical paths (/, /home, /var, /var/cache/pacman/pkg) using 'df -h'. Returns disk usage info with warnings if usage exceeds 80% or 90%.
    async def check_disk_space() -> Dict[str, Any]:
        """
        Check disk space for critical paths.
    
        Returns:
            Dict with disk usage for /, /home, /var, /var/cache/pacman/pkg
        """
        logger.info("Checking disk space")
    
        paths_to_check = ["/", "/home", "/var"]
    
        if IS_ARCH:
            paths_to_check.append("/var/cache/pacman/pkg")
    
        disk_info = {}
    
        try:
            for path in paths_to_check:
                if not Path(path).exists():
                    continue
    
                exit_code, stdout, _ = await run_command(
                    ["df", "-h", path],
                    timeout=5,
                    check=False
                )
    
                if exit_code == 0:
                    lines = stdout.strip().split('\n')
                    if len(lines) >= 2:
                        # Parse df output
                        parts = lines[1].split()
                        if len(parts) >= 5:
                            disk_info[path] = {
                                "size": parts[1],
                                "used": parts[2],
                                "available": parts[3],
                                "use_percent": parts[4],
                                "mounted_on": parts[5] if len(parts) > 5 else path
                            }
    
                            # Check if space is critically low
                            use_pct = int(parts[4].rstrip('%'))
                            if use_pct > 90:
                                disk_info[path]["warning"] = "Critical: Less than 10% free"
                            elif use_pct > 80:
                                disk_info[path]["warning"] = "Low: Less than 20% free"
    
            logger.info(f"Checked disk space for {len(disk_info)} paths")
    
            return {
                "disk_usage": disk_info,
                "paths_checked": len(disk_info)
            }
    
        except Exception as e:
            logger.error(f"Failed to check disk space: {e}")
            return create_error_response(
                "DiskCheckError",
                f"Failed to check disk space: {str(e)}"
            )
  • Helper: get_pacman_cache_stats() - Analyzes pacman cache in /var/cache/pacman/pkg. Counts packages and calculates total cache size.
    async def get_pacman_cache_stats() -> Dict[str, Any]:
        """
        Analyze pacman package cache.
    
        Returns:
            Dict with cache size, package count, statistics
        """
        if not IS_ARCH:
            return create_error_response(
                "NotSupported",
                "Pacman cache analysis is only available on Arch Linux"
            )
    
        logger.info("Analyzing pacman cache")
    
        cache_dir = Path("/var/cache/pacman/pkg")
    
        try:
            if not cache_dir.exists():
                return create_error_response(
                    "NotFound",
                    "Pacman cache directory not found"
                )
    
            # Count packages
            pkg_files = list(cache_dir.glob("*.pkg.tar.*"))
            pkg_count = len(pkg_files)
    
            # Calculate total size
            total_size = sum(f.stat().st_size for f in pkg_files)
            total_size_mb = total_size / (1024 * 1024)
            total_size_gb = total_size_mb / 1024
    
            logger.info(f"Cache: {pkg_count} packages, {total_size_gb:.2f} GB")
    
            return {
                "cache_dir": str(cache_dir),
                "package_count": pkg_count,
                "total_size_bytes": total_size,
                "total_size_mb": round(total_size_mb, 2),
                "total_size_gb": round(total_size_gb, 2)
            }
    
        except Exception as e:
            logger.error(f"Failed to analyze cache: {e}")
            return create_error_response(
                "CacheAnalysisError",
                f"Failed to analyze pacman cache: {str(e)}"
            )
  • Tool is exported from the package via __init__.py: imported from .system and included in __all__.
    from .system import (
        get_system_info,
        check_disk_space,
        get_pacman_cache_stats,
        analyze_storage,
        check_failed_services,
        get_boot_logs,
        diagnose_system,
    )
  • Tool metadata registration: defines analyze_storage as a 'monitoring' tool with 'read' permission in the 'diagnose' workflow.
    "analyze_storage": ToolMetadata(
        name="analyze_storage",
        category="monitoring",
        platform="any",
        permission="read",
        workflow="diagnose",
        related_tools=["check_failed_services"],
        prerequisite_tools=[]
    ),
Behavior4/5

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

Annotations already declare readOnlyHint=true. The description reinforces this with '[MONITORING]' and describes the actions as checks and analyses. It adds platform-specific behavior for cache_stats, which is beyond annotations. No mention of potential permissions (e.g., sudo) but adequate given read-only nature.

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?

Two sentences: first states overall purpose and lists actions, second specifies platform constraints. No wasted words, front-loaded with key information. Efficient and clear.

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?

Despite no output schema, the description covers all necessary context: tool category, available actions, and platform-specific usage. For a simple tool with one parameter and no nested objects, the description is sufficient for an AI agent to select and invoke 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?

Schema has one required parameter 'action' with enum values and description. The description enriches each enum value with behavior: 'disk_usage (check disk space for critical paths)', 'cache_stats (analyze pacman package cache)'. This provides meaning beyond the schema's enum labels.

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 is a monitoring tool for storage analysis, listing two specific actions ('disk_usage', 'cache_stats') with brief descriptions. It distinguishes from sibling tools by prefixing '[MONITORING]' and specifying platform constraints.

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 provides per-action platform constraints: 'Works on any system for disk_usage, Arch only for cache_stats.' It gives clear guidance on when each action is applicable, but does not explicitly differentiate from sibling tools like 'analyze_makepkg_conf' or 'diagnose_system'.

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/nihalxkumar/arch-linux-mcp'

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