Skip to main content
Glama
saksham0712

MCP Complete Implementation Guide

by saksham0712

list_directory

Lists the contents of a specified directory path to view files and subdirectories within a file system.

Instructions

List the contents of a directory

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesThe path to the directory to list

Implementation Reference

  • Implements the list_directory tool logic: reads directory using fs.readdir, formats items with name, type, path, returns as JSON text content.
    async listDirectory(dirPath) {
      try {
        const items = await fs.readdir(dirPath, { withFileTypes: true });
        const listing = items.map(item => ({
          name: item.name,
          type: item.isDirectory() ? 'directory' : 'file',
          path: path.join(dirPath, item.name),
        }));
    
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(listing, null, 2),
            },
          ],
        };
      } catch (error) {
        throw new Error(`Failed to list directory: ${error.message}`);
      }
    }
  • server.js:76-89 (registration)
    Registers the list_directory tool in the ListTools response, including name, description, and input schema.
    {
      name: 'list_directory',
      description: 'List the contents of a directory',
      inputSchema: {
        type: 'object',
        properties: {
          path: {
            type: 'string',
            description: 'The path to the directory to list',
          },
        },
        required: ['path'],
      },
    },
  • Defines the input schema for list_directory tool: requires 'path' string.
    inputSchema: {
      type: 'object',
      properties: {
        path: {
          type: 'string',
          description: 'The path to the directory to list',
        },
      },
      required: ['path'],
    },
  • Python implementation of list_directory handler: uses Path.iterdir to list items, formats similarly, returns JSON text.
    async def list_directory(self, dir_path: str) -> list[types.TextContent]:
        """List directory contents"""
        try:
            path = Path(dir_path)
            items = []
            for item in path.iterdir():
                items.append({
                    "name": item.name,
                    "type": "directory" if item.is_dir() else "file",
                    "path": str(item),
                })
            return [types.TextContent(type="text", text=json.dumps(items, indent=2))]
        except Exception as error:
            raise Exception(f"Failed to list directory: {str(error)}")
  • server.py:104-116 (registration)
    Registers list_directory tool using types.Tool in the list_tools handler.
    types.Tool(
        name="list_directory",
        description="List the contents of a directory",
        inputSchema={
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "The path to the directory to list",
                }
            },
            "required": ["path"],
        },
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 offers minimal behavioral insight. It implies a read-only operation ('List') but doesn't disclose critical traits like error handling (e.g., if path doesn't exist), output format (e.g., list structure, metadata included), or performance considerations (e.g., large directories). This is inadequate for a tool with no annotation support.

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 with zero wasted words. It's front-loaded with the core action and resource, making it easy to parse quickly. Every word earns its place by directly contributing to understanding the tool's purpose.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given no annotations, no output schema, and a simple input schema, the description is incomplete. It lacks details on behavioral aspects (e.g., what 'contents' means, error cases) and usage context, which are essential for an agent to invoke this tool correctly in real scenarios. The simplicity of the tool doesn't excuse these gaps.

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 the 'path' parameter fully. The description adds no additional meaning beyond implying the parameter is for directory listing, which the schema's description ('The path to the directory to list') already covers. This meets the baseline for high schema coverage.

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 ('List') and resource ('contents of a directory'), making the purpose immediately understandable. It distinguishes from siblings like 'read_file' (which reads file contents) and 'execute_command' (which runs commands). However, it doesn't specify what 'contents' includes (files, subdirectories, metadata), which prevents a perfect score.

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?

No guidance is provided on when to use this tool versus alternatives. The description doesn't mention prerequisites (e.g., directory existence, permissions), exclusions (e.g., not for file reading), or comparisons to siblings like 'get_system_info' (which might provide system-level directory info). This leaves the agent with minimal context for tool selection.

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/saksham0712/MCP'

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