Skip to main content
Glama

list_directory

Browse and filter directory contents with adjustable depth control to manage file organization in your knowledge system.

Instructions

List directory contents with filtering and depth control.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
dir_nameNo/
depthNo
file_name_globNo
projectNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The primary handler for the 'list_directory' MCP tool. This async function, decorated with @mcp.tool(), handles the tool execution: resolves the project context, calls the /directory/list API endpoint with parameters, processes the response nodes, and formats a user-friendly directory listing grouped by directories and files with metadata.
    @mcp.tool(
        description="List directory contents with filtering and depth control.",
    )
    async def list_directory(
        dir_name: str = "/",
        depth: int = 1,
        file_name_glob: Optional[str] = None,
        project: Optional[str] = None,
        context: Context | None = None,
    ) -> str:
        """List directory contents from the knowledge base with optional filtering.
    
        This tool provides 'ls' functionality for browsing the knowledge base directory structure.
        It can list immediate children or recursively explore subdirectories with depth control,
        and supports glob pattern filtering for finding specific files.
    
        Args:
            dir_name: Directory path to list (default: root "/")
                     Examples: "/", "/projects", "/research/ml"
            depth: Recursion depth (1-10, default: 1 for immediate children only)
                   Higher values show subdirectory contents recursively
            file_name_glob: Optional glob pattern for filtering file names
                           Examples: "*.md", "*meeting*", "project_*"
            project: Project name to list directory from. Optional - server will resolve using hierarchy.
                    If unknown, use list_memory_projects() to discover available projects.
            context: Optional FastMCP context for performance caching.
    
        Returns:
            Formatted listing of directory contents with file metadata
    
        Examples:
            # List root directory contents
            list_directory()
    
            # List specific folder
            list_directory(dir_name="/projects")
    
            # Find all markdown files
            list_directory(file_name_glob="*.md")
    
            # Deep exploration of research folder
            list_directory(dir_name="/research", depth=3)
    
            # Find meeting notes in projects folder
            list_directory(dir_name="/projects", file_name_glob="*meeting*")
    
            # Explicit project specification
            list_directory(project="work-docs", dir_name="/projects")
    
        Raises:
            ToolError: If project doesn't exist or directory path is invalid
        """
        track_mcp_tool("list_directory")
        async with get_client() as client:
            active_project = await get_active_project(client, project, context)
    
            # Prepare query parameters
            params = {
                "dir_name": dir_name,
                "depth": str(depth),
            }
            if file_name_glob:
                params["file_name_glob"] = file_name_glob
    
            logger.debug(
                f"Listing directory '{dir_name}' in project {project} with depth={depth}, glob='{file_name_glob}'"
            )
    
            # Call the API endpoint
            response = await call_get(
                client,
                f"/v2/projects/{active_project.external_id}/directory/list",
                params=params,
            )
    
            nodes = response.json()
    
            if not nodes:
                filter_desc = ""
                if file_name_glob:
                    filter_desc = f" matching '{file_name_glob}'"
                return f"No files found in directory '{dir_name}'{filter_desc}"
    
            # Format the results
            output_lines = []
            if file_name_glob:
                output_lines.append(
                    f"Files in '{dir_name}' matching '{file_name_glob}' (depth {depth}):"
                )
            else:
                output_lines.append(f"Contents of '{dir_name}' (depth {depth}):")
            output_lines.append("")
    
            # Group by type and sort
            directories = [n for n in nodes if n["type"] == "directory"]
            files = [n for n in nodes if n["type"] == "file"]
    
            # Sort by name
            directories.sort(key=lambda x: x["name"])
            files.sort(key=lambda x: x["name"])
    
            # Display directories first
            for node in directories:
                path_display = node["directory_path"]
                output_lines.append(f"📁 {node['name']:<30} {path_display}")
    
            # Add separator if we have both directories and files
            if directories and files:
                output_lines.append("")
    
            # Display files with metadata
            for node in files:
                path_display = node["directory_path"]
                title = node.get("title", "")
                updated = node.get("updated_at", "")
    
                # Remove leading slash if present, requesting the file via read_note does not use the beginning slash'
                if path_display.startswith("/"):
                    path_display = path_display[1:]
    
                # Format date if available
                date_str = ""
                if updated:
                    try:
                        from datetime import datetime
    
                        dt = datetime.fromisoformat(updated.replace("Z", "+00:00"))
                        date_str = dt.strftime("%Y-%m-%d")
                    except Exception:  # pragma: no cover
                        date_str = updated[:10] if len(updated) >= 10 else ""
    
                # Create formatted line
                file_line = f"📄 {node['name']:<30} {path_display}"
                if title and title != node["name"]:
                    file_line += f" | {title}"
                if date_str:
                    file_line += f" | {date_str}"
    
                output_lines.append(file_line)
    
            # Add summary
            output_lines.append("")
            total_count = len(directories) + len(files)
            summary_parts = []
            if directories:
                summary_parts.append(
                    f"{len(directories)} director{'y' if len(directories) == 1 else 'ies'}"
                )
            if files:
                summary_parts.append(f"{len(files)} file{'s' if len(files) != 1 else ''}")
    
            output_lines.append(f"Total: {total_count} items ({', '.join(summary_parts)})")
    
            return "\n".join(output_lines)
  • The import statement in the tools package __init__.py that loads the list_directory.py module. This executes the module's code, including the @mcp.tool() decorator on the handler function, thereby registering the 'list_directory' tool with the global MCP server instance.
    from basic_memory.mcp.tools.list_directory import list_directory
Behavior2/5

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

With no annotations provided, the description carries full burden but offers minimal behavioral insight. It mentions 'filtering and depth control' but doesn't disclose critical details like whether this is a read-only operation, what permissions are needed, how results are structured, or any rate limits. For a tool with 4 parameters and no annotation coverage, this is inadequate.

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 extremely concise (one sentence) and front-loaded with the core purpose. Every word earns its place, with no redundant or vague language, making it efficient for quick understanding.

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

Completeness3/5

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

Given the tool's moderate complexity (4 parameters, no annotations, but with an output schema), the description is incomplete. The output schema reduces the need to explain return values, but the description lacks guidance on usage, parameter details, and behavioral context, leaving significant gaps for effective tool selection.

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 description coverage is 0%, so the description must compensate but fails to do so. It mentions 'filtering' (hinting at 'file_name_glob') and 'depth control' (hinting at 'depth'), but doesn't explain the purpose of 'dir_name' or 'project', nor provide any syntax or format details. With 4 undocumented parameters, this adds minimal value beyond the schema.

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 tool's purpose with specific verbs ('list directory contents') and resources ('directory'), and mentions capabilities ('filtering and depth control'). However, it doesn't explicitly differentiate from sibling tools like 'search' or 'fetch' that might also retrieve file information.

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 is provided on when to use this tool versus alternatives like 'search', 'fetch', or 'read_content'. The description mentions filtering capabilities but doesn't specify scenarios where this tool is preferred over others or any prerequisites for use.

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/basicmachines-co/basic-memory'

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