Skip to main content
Glama
safurrier

MCP Filesystem Server

list_directory

Retrieve detailed file and directory listings from a specified path, with options to filter by pattern, include hidden files, and choose output format.

Instructions

Get a detailed listing of files and directories in a path.

Args:
    path: Path to the directory
    include_hidden: Whether to include hidden files (starting with .)
    pattern: Optional glob pattern to filter entries
    format: Output format ('text' or 'json')
    ctx: MCP context

Returns:
    Formatted directory listing

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYes
include_hiddenNo
patternNo
formatNotext

Implementation Reference

  • Primary MCP tool handler and registration for 'list_directory'. Handles parameters, delegates to FileOperations.list_directory() or list_directory_formatted() based on output format, and returns JSON or text listing.
    @mcp.tool()
    async def list_directory(
        path: str,
        ctx: Context,
        include_hidden: bool = False,
        pattern: Optional[str] = None,
        format: str = "text",
    ) -> str:
        """Get a detailed listing of files and directories in a path.
    
        Args:
            path: Path to the directory
            include_hidden: Whether to include hidden files (starting with .)
            pattern: Optional glob pattern to filter entries
            format: Output format ('text' or 'json')
            ctx: MCP context
    
        Returns:
            Formatted directory listing
        """
        try:
            components = get_components()
            if format.lower() == "json":
                entries = await components["operations"].list_directory(
                    path, include_hidden, pattern
                )
                return json.dumps(entries, indent=2)
            else:
                return await components["operations"].list_directory_formatted(
                    path, include_hidden, pattern
                )
        except Exception as e:
            return f"Error listing directory: {str(e)}"
  • Core helper function in FileOperations that performs the actual directory listing: validates path, iterates entries, filters by hidden/pattern, creates FileInfo, returns list of dicts.
    async def list_directory(
        self,
        path: Union[str, Path],
        include_hidden: bool = False,
        pattern: Optional[str] = None,
    ) -> List[Dict]:
        """List directory contents.
    
        Args:
            path: Path to the directory
            include_hidden: Whether to include hidden files (starting with .)
            pattern: Optional glob pattern to filter files
    
        Returns:
            List of file/directory information dictionaries
    
        Raises:
            ValueError: If path is outside allowed directories or not a directory
            PermissionError: If directory cannot be read
        """
        abs_path, allowed = await self.validator.validate_path(path)
        if not allowed:
            raise ValueError(f"Path outside allowed directories: {path}")
    
        if not abs_path.is_dir():
            raise ValueError(f"Not a directory: {path}")
    
        results = []
    
        try:
            entries = await anyio.to_thread.run_sync(list, abs_path.iterdir())
    
            for entry in entries:
                # Skip hidden files if not requested
                if not include_hidden and entry.name.startswith("."):
                    continue
    
                # Apply pattern filter if specified
                if pattern and not entry.match(pattern):
                    continue
    
                try:
                    info = FileInfo(entry)
                    results.append(info.to_dict())
                except (PermissionError, FileNotFoundError):
                    # Skip files we can't access
                    pass
    
            return results
    
        except PermissionError as e:
            raise ValueError(f"Cannot read directory: {e}")
  • Helper function that calls list_directory() and formats the output as a sorted, human-readable text listing with type, size, and modification time.
    async def list_directory_formatted(
        self,
        path: Union[str, Path],
        include_hidden: bool = False,
        pattern: Optional[str] = None,
    ) -> str:
        """List directory contents in a formatted string.
    
        Args:
            path: Path to the directory
            include_hidden: Whether to include hidden files
            pattern: Optional glob pattern to filter files
    
        Returns:
            Formatted string with directory contents
        """
        entries = await self.list_directory(path, include_hidden, pattern)
    
        if not entries:
            return "Directory is empty"
    
        # Format the output
        result = []
        for entry in sorted(entries, key=lambda x: (not x["is_directory"], x["name"])):
            prefix = "[DIR] " if entry["is_directory"] else "[FILE]"
            size = "" if entry["is_directory"] else f" ({entry['size']:,} bytes)"
            modified = datetime.fromisoformat(entry["modified"]).strftime(
                "%Y-%m-%d %H:%M:%S"
            )
            result.append(f"{prefix} {entry['name']}{size} - {modified}")
    
        return "\n".join(result)
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 lacks critical behavioral details. It mentions output formatting but doesn't disclose pagination, rate limits, error conditions, or what 'detailed listing' includes (e.g., file sizes, permissions). For a read operation with 4 parameters, this leaves significant gaps in understanding tool behavior.

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

Conciseness4/5

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

The description is well-structured with a clear purpose statement followed by parameter explanations. Every sentence adds value, though the 'ctx: MCP context' line is redundant since MCP context is implicit. Overall efficient with minimal waste.

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 4 parameters with no schema descriptions and no output schema, the description does well on parameters but lacks completeness. It doesn't explain return format details, error handling, or behavioral constraints. For a directory listing tool with filtering options, more context about output structure and limitations would be helpful.

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

Parameters5/5

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

The description adds substantial meaning beyond the 0% schema coverage. It explains each parameter's purpose: path as directory location, include_hidden for dot-files, pattern as glob filter, and format as output type. This fully compensates for the schema's lack of descriptions, making parameters understandable.

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 the specific verb ('Get a detailed listing') and resource ('files and directories in a path'), distinguishing it from siblings like directory_tree (hierarchical view) or search_files (content-based). It precisely defines what the tool does without being vague or tautological.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage through the parameter explanations (e.g., pattern for filtering, format for output), but doesn't explicitly state when to use this tool versus alternatives like list_allowed_directories or directory_tree. There's no guidance on prerequisites or exclusions, leaving usage context to inference.

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/safurrier/mcp-filesystem'

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