Skip to main content
Glama

list_directory

List directory entries with metadata while enforcing path and depth restrictions to prevent unauthorized file access.

Instructions

List directory entries with metadata, honoring path and depth policy.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYes
ctxNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Main handler for list_directory tool. Resolves path, checks policy (path whitelist/blocklist, depth limit), reads directory entries with metadata (name, type, size, modification time), and returns formatted listing.
    def list_directory(path: str, ctx: Context | None = None) -> str:
        """List directory entries with metadata, honoring path and depth policy."""
        context_tokens = activate_runtime_context(ctx)
        path = str(pathlib.Path(WORKSPACE_ROOT) / path) if not os.path.isabs(path) else path
    
        try:
            refresh_policy_if_changed()
            path_check = check_path_policy(path, tool="list_directory")
            if path_check:
                result = PolicyResult(allowed=False, reason=path_check[0], decision_tier="blocked", matched_rule=path_check[1])
            else:
                result = PolicyResult(allowed=True, reason="allowed", decision_tier="allowed", matched_rule=None)
    
            if result.allowed:
                if not os.path.exists(path):
                    append_log_entry(build_log_entry("list_directory", result, path=path, error="path not found"))
                    return f"Error: path not found: {path}"
    
                if not os.path.isdir(path):
                    append_log_entry(build_log_entry("list_directory", result, path=path, error="not a directory"))
                    return f"Error: '{path}' is a file, not a directory"
    
                depth = relative_depth(path)
                max_depth = POLICY.get("allowed", {}).get("max_directory_depth", 5)
                if depth > max_depth:
                    result = PolicyResult(
                        allowed=False,
                        reason=f"Directory depth {depth} exceeds the policy limit of {max_depth} (allowed.max_directory_depth): '{path}'",
                        decision_tier="blocked",
                        matched_rule="allowed.max_directory_depth",
                    )
    
            append_log_entry(build_log_entry("list_directory", result, path=path))
            if not result.allowed:
                return f"[POLICY BLOCK] {result.reason}"
    
            lines = [f"Contents of {path}:"]
            try:
                entries = sorted(os.scandir(path), key=lambda e: (e.is_file(), e.name))
            except OSError as e:
                return f"Error reading directory: {e}"
    
            for entry in entries:
                try:
                    stat = entry.stat(follow_symlinks=False)
                    mtime = datetime.datetime.fromtimestamp(stat.st_mtime, datetime.UTC).isoformat().replace("+00:00", "Z")
                    kind = "file" if entry.is_file(follow_symlinks=False) else "directory"
                    size = f"{stat.st_size} bytes" if kind == "file" else "-"
                    lines.append(f"  {entry.name}  [{kind}]  size={size}  modified={mtime}")
                except OSError:
                    lines.append(f"  {entry.name}  [unreadable]")
    
            if len(lines) == 1:
                lines.append("  (empty)")
    
            return "\n".join(lines)
        finally:
            reset_runtime_context(context_tokens)
  • src/server.py:21-31 (registration)
    list_directory is registered as an MCP tool via mcp.tool()(tool) decoration loop in the FastMCP server.
    for tool in [
        server_info,
        restore_backup,
        execute_command,
        read_file,
        write_file,
        edit_file,
        delete_file,
        list_directory,
    ]:
        mcp.tool()(tool)
  • list_directory is exported from the tools package via __init__.py.
    from .command_tools import execute_command, server_info
    from .file_tools import delete_file, edit_file, list_directory, read_file, write_file
    from .restore_tools import restore_backup
    
    __all__ = [
        "server_info",
        "execute_command",
        "read_file",
        "write_file",
        "edit_file",
        "delete_file",
        "list_directory",
        "restore_backup",
    ]
  • list_directory is listed as one of the AIRG MCP tools for configuration management (used for generating MCP config for agent platforms).
    AIRG_MCP_TOOLS = [
        "server_info",
        "restore_backup",
        "execute_command",
        "read_file",
        "write_file",
        "edit_file",
        "delete_file",
        "list_directory",
    ]
Behavior2/5

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

No annotations are provided, so description must cover behavior. It states 'honoring path and depth policy' but does not explain what that policy is, nor whether the operation is read-only, paginated, or recursive.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness3/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Single sentence is concise and front-loaded with purpose. However, it sacrifices necessary detail for brevity.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given no annotations, two parameters, and an output schema, the description should clarify behavior, parameter roles, and output meaning. It fails to explain the depth policy and the optional ctx parameter.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 0%, so description must explain parameters. It mentions 'path' indirectly but does not describe 'ctx' or how depth policy affects listing. Minimal addition beyond schema structure.

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?

Description uses specific verb 'list' and resource 'directory entries with metadata'. It clearly states the action and what is returned, distinguishing it from file manipulation siblings like delete_file and write_file.

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?

No guidance on when to use this tool versus alternatives (e.g., read_file for file content). The mention of 'depth policy' implies constraints but is not explained.

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/jimmyracheta/ai-runtime-guard'

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