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

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

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