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

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

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()
Behavior2/5

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

No annotations are provided, so the description carries full burden. It states what the tool does but lacks behavioral details: it doesn't specify if this is a read-only operation, what happens with invalid paths, whether it recursively searches subdirectories, what format the output takes (e.g., list of filenames, full paths), or any error conditions. The description is minimal and doesn't disclose important operational traits.

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 extremely concise and well-structured: a clear purpose statement followed by a brief parameter explanation. Every sentence earns its place, with no redundant information. It's front-loaded with the core functionality, making it easy to scan and understand quickly.

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 that there's an output schema (which presumably describes the return format), the description doesn't need to explain return values. However, for a tool with no annotations and only basic parameter documentation, the description is somewhat incomplete: it doesn't address error handling, recursion behavior, or file filtering details beyond 'Python files'. It's minimally adequate but leaves gaps in understanding the tool's full behavior.

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

Parameters4/5

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

The description adds meaningful context for the single parameter: it explains that directory_path is 'Path to directory (empty for working directory)', which clarifies the default behavior when the parameter is omitted. Since schema description coverage is 0% and there's only one parameter, this compensates well. However, it doesn't detail path format requirements (e.g., absolute vs. relative) or validation rules.

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 'List all Python files in a directory' which specifies the verb (list), resource (Python files), and scope (directory). It distinguishes from siblings like list_installed_packages or list_sessions by focusing specifically on Python files in a filesystem directory. However, it doesn't explicitly contrast with all siblings, so it's not a perfect 5.

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. It doesn't mention when to choose list_directory over other file-related tools like read_file or run_python_file, nor does it specify prerequisites or exclusions. The only contextual hint is the sibling list, but the description itself offers no usage instructions.

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

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