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]}`;
    }

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