Skip to main content
Glama
yzfly

MCP Python Interpreter

by yzfly

list_directory

Lists Python files in a specified directory to help users identify available scripts and modules for execution or analysis.

Instructions

List all Python files in a directory.

Args:
    directory_path: Path to directory (empty for working directory)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
directory_pathNo

Implementation Reference

  • The handler function decorated with @mcp.tool() that implements the list_directory tool logic. It lists Python files in the given directory, groups them by subdirectories, and formats the output with sizes.
    @mcp.tool()
    def list_directory(directory_path: str = "") -> str:
        """
        List all Python files in a directory.
        
        Args:
            directory_path: Path to directory (empty for working directory)
        """
        try:
            if not directory_path:
                path = WORKING_DIR
            else:
                path = Path(directory_path)
                if path.is_absolute():
                    if not is_path_allowed(path):
                        return f"Access denied: Can only list files in working directory: {WORKING_DIR}"
                else:
                    path = WORKING_DIR / directory_path
                    
            if not path.exists():
                return f"Error: Directory '{directory_path}' not found"
                
            if not path.is_dir():
                return f"Error: '{directory_path}' is not a directory"
                
            files = find_python_files(path)
            
            if not files:
                return f"No Python files found in {directory_path or 'working directory'}"
                
            result = f"Python files in: {directory_path or str(WORKING_DIR)}\n\n"
            
            files_by_dir = {}
            base_dir = path if ALLOW_SYSTEM_ACCESS else WORKING_DIR
            
            for file in files:
                file_path = Path(file["path"])
                try:
                    relative_path = file_path.relative_to(base_dir)
                    parent = str(relative_path.parent)
                    if parent == ".":
                        parent = "(root)"
                except ValueError:
                    parent = str(file_path.parent)
                    
                if parent not in files_by_dir:
                    files_by_dir[parent] = []
                    
                files_by_dir[parent].append({
                    "name": file["name"],
                    "size": file["size"]
                })
                
            for dir_name, dir_files in sorted(files_by_dir.items()):
                result += f"๐Ÿ“ {dir_name}:\n"
                for file in sorted(dir_files, key=lambda x: x["name"]):
                    size_kb = round(file["size"] / 1024, 1)
                    result += f"  ๐Ÿ“„ {file['name']} ({size_kb} KB)\n"
                result += "\n"
                
            return result
        except Exception as e:
            return f"Error listing directory: {str(e)}"
  • Helper function used by list_directory to recursively find all Python (*.py) files in a directory and collect their path, name, size, and modification time.
    def find_python_files(directory: Path) -> List[Dict[str, str]]:
        """Find all Python files in a directory."""
        files = []
        
        if not directory.exists():
            return files
        
        for path in directory.rglob("*.py"):
            if path.is_file():
                files.append({
                    "path": str(path),
                    "name": path.name,
                    "size": path.stat().st_size,
                    "modified": path.stat().st_mtime
                })
        
        return files
  • The @mcp.tool() decorator registers the list_directory function as an MCP tool.
    @mcp.tool()

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/yzfly/mcp-python-interpreter'

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