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"],
        },

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