Skip to main content
Glama

fast_list_directory

List directory contents with pagination and filtering to manage large file collections efficiently.

Instructions

Lists the contents of a directory (with auto-chunking and pagination support)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesDirectory path
pageNoPage number
page_sizeNoNumber of items per page
patternNoFilename filter pattern
show_hiddenNoShow hidden files
sort_byNoSort byname
reverseNoReverse sort order
continuation_tokenNoContinuation token from a previous call
auto_chunkNoEnable auto-chunking

Implementation Reference

  • The handler function that implements the core logic for the 'fast_list_directory' tool. It resolves the path safely, reads directory entries, filters and sorts them based on parameters, paginates the results, and enriches items with stats.
    async function handleListDirectory(args: any) {
      const { path: dirPath, page = 1, page_size, pattern, show_hidden = false, sort_by = 'name', reverse = false } = args;
      
      const safePath_resolved = safePath(dirPath);
      const stats = await fs.stat(safePath_resolved);
      
      if (!stats.isDirectory()) {
        throw new Error('Path is not a directory');
      }
      
      const pageSize = page_size ? Math.min(page_size, CLAUDE_MAX_DIR_ITEMS) : 50;
      const entries = await fs.readdir(safePath_resolved, { withFileTypes: true });
      
      let filteredEntries = entries.filter(entry => {
        if (!show_hidden && entry.name.startsWith('.')) return false;
        if (shouldExcludePath(path.join(safePath_resolved, entry.name))) return false;
        if (pattern) {
          return entry.name.toLowerCase().includes(pattern.toLowerCase());
        }
        return true;
      });
      
      // 정렬
      filteredEntries.sort((a, b) => {
        let comparison = 0;
        
        switch (sort_by) {
          case 'name':
            comparison = a.name.localeCompare(b.name);
            break;
          case 'type':
            const aType = a.isDirectory() ? 'directory' : 'file';
            const bType = b.isDirectory() ? 'directory' : 'file';
            comparison = aType.localeCompare(bType);
            break;
          default:
            comparison = a.name.localeCompare(b.name);
        }
        
        return reverse ? -comparison : comparison;
      });
      
      const startIdx = (page - 1) * pageSize;
      const endIdx = startIdx + pageSize;
      const pageEntries = filteredEntries.slice(startIdx, endIdx);
      
      const items = await Promise.all(pageEntries.map(async (entry) => {
        try {
          const fullPath = path.join(safePath_resolved, entry.name);
          const itemStats = await fs.stat(fullPath);
          
          return {
            name: entry.name,
            type: entry.isDirectory() ? 'directory' : 'file',
            size: entry.isFile() ? itemStats.size : null,
            size_readable: entry.isFile() ? formatSize(itemStats.size) : null,
            modified: itemStats.mtime.toISOString(),
            created: itemStats.birthtime.toISOString(),
            permissions: itemStats.mode,
            path: fullPath
          };
        } catch {
          return {
            name: entry.name,
            type: entry.isDirectory() ? 'directory' : 'file',
            size: null,
            size_readable: null,
            modified: null,
            created: null,
            permissions: null,
            path: path.join(safePath_resolved, entry.name)
          };
        }
      }));
      
      return {
        path: safePath_resolved,
        items: items,
        page: page,
        page_size: pageSize,
        total_count: filteredEntries.length,
        total_pages: Math.ceil(filteredEntries.length / pageSize),
        has_more: endIdx < filteredEntries.length,
        sort_by: sort_by,
        reverse: reverse,
        timestamp: new Date().toISOString()
      };
    }
  • The input schema definition for the 'fast_list_directory' tool, including parameters for path, pagination, filtering, sorting, and visibility options.
    {
      name: 'fast_list_directory',
      description: '디렉토리 목록을 조회합니다 (페이징 지원)',
      inputSchema: {
        type: 'object',
        properties: {
          path: { type: 'string', description: '디렉토리 경로' },
          page: { type: 'number', description: '페이지 번호', default: 1 },
          page_size: { type: 'number', description: '페이지당 항목 수' },
          pattern: { type: 'string', description: '파일명 필터 패턴' },
          show_hidden: { type: 'boolean', description: '숨김 파일 표시', default: false },
          sort_by: { type: 'string', description: '정렬 기준', enum: ['name', 'size', 'modified', 'type'], default: 'name' },
          reverse: { type: 'boolean', description: '역순 정렬', default: false }
        },
        required: ['path']
      }
    },
  • api/server.ts:329-331 (registration)
    The switch case that registers and dispatches to the 'fast_list_directory' handler during tool calls.
    case 'fast_list_directory':
      result = await handleListDirectory(args);
      break;
  • Helper function used by the handler to safely resolve paths and enforce access restrictions.
    function safePath(inputPath: string): string {
      if (!isPathAllowed(inputPath)) {
        throw new Error(`Access denied to path: ${inputPath}`);
      }
      return path.resolve(inputPath);
    }
  • Helper function used to format file sizes in a human-readable format within directory listings.
    function formatSize(bytes: number): string {
      const units = ['B', 'KB', 'MB', 'GB', 'TB'];
      let size = bytes;
      let unitIndex = 0;
      
      while (size >= 1024 && unitIndex < units.length - 1) {
        size /= 1024;
        unitIndex++;
      }
      
      return `${size.toFixed(2)} ${units[unitIndex]}`;
    }
Behavior3/5

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

With no annotations provided, the description carries full burden. It discloses key behavioral traits: 'auto-chunking and pagination support' indicates handling of large result sets. However, it doesn't mention performance characteristics, error conditions (e.g., invalid paths), permission requirements, rate limits, or what the output format looks like. The description adds some value but leaves significant behavioral aspects unspecified.

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 a single, efficient sentence that front-loads the core functionality ('Lists the contents of a directory') and adds important behavioral context in parentheses. Every word earns its place, with zero wasted text. The structure is optimal for quick comprehension.

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 complexity (9 parameters, no annotations, no output schema), the description is minimally adequate. It mentions key behavioral aspects (chunking/pagination) but doesn't explain the return format, error handling, or performance considerations. For a tool with this many configuration options and no output schema, more context about what to expect would be helpful, though the 100% schema coverage helps compensate.

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

Parameters3/5

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

Schema description coverage is 100%, so the schema already documents all 9 parameters thoroughly. The description adds no additional parameter semantics beyond what's in the schema - it doesn't explain relationships between parameters (e.g., how 'auto_chunk' interacts with 'page' and 'continuation_token') or provide usage examples. Baseline 3 is appropriate when schema does the heavy lifting.

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 verb ('Lists') and resource ('contents of a directory'), making the purpose immediately understandable. It distinguishes from siblings like 'fast_get_directory_tree' (which provides tree structure) and 'fast_search_files' (which searches content), though it doesn't explicitly mention these distinctions. The description is specific but lacks explicit sibling differentiation.

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?

The description provides no guidance on when to use this tool versus alternatives like 'fast_get_directory_tree' (for hierarchical view) or 'fast_search_files' (for content-based filtering). It mentions 'auto-chunking and pagination support' which hints at usage for large directories, but doesn't specify when to choose this over simpler listing tools or when pagination is necessary.

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

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