Skip to main content
Glama

delete_directory

Remove a directory by specifying its path, with an option to delete contents recursively. Supports both relative and absolute paths for flexible file management.

Instructions

Removes a directory. Optionally removes recursively. Accepts relative or absolute paths.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesThe path to the directory to delete. Can be relative or absolute.
recursiveNoIf true, delete the directory and all its contents. If false, only delete if the directory is empty.

Implementation Reference

  • Core handler function that executes the delete directory logic: resolves path, checks existence and type, deletes recursively or if empty using fs.promises APIs, handles various errors with McpError.
    export const deleteDirectoryLogic = async (input: DeleteDirectoryInput, context: RequestContext): Promise<DeleteDirectoryOutput> => {
      const { path: requestedPath, recursive } = input;
      const logicContext = { ...context, tool: 'deleteDirectoryLogic', recursive };
      logger.debug(`deleteDirectoryLogic: Received request to delete directory "${requestedPath}"`, logicContext);
    
      // Resolve the path
      const absolutePath = serverState.resolvePath(requestedPath, context);
      logger.debug(`deleteDirectoryLogic: Resolved path to "${absolutePath}"`, { ...logicContext, requestedPath });
    
      try {
        // Check if the path exists and is a directory before attempting deletion
        let stats;
        try {
          stats = await fs.stat(absolutePath);
        } catch (statError: any) {
          if (statError.code === 'ENOENT') {
            logger.warning(`deleteDirectoryLogic: Directory not found at "${absolutePath}"`, { ...logicContext, requestedPath });
            throw new McpError(BaseErrorCode.NOT_FOUND, `Directory not found at path: ${absolutePath}`, { ...logicContext, requestedPath, resolvedPath: absolutePath, originalError: statError });
          }
          throw statError; // Re-throw other stat errors
        }
    
        if (!stats.isDirectory()) {
          logger.warning(`deleteDirectoryLogic: Path is not a directory "${absolutePath}"`, { ...logicContext, requestedPath });
          throw new McpError(BaseErrorCode.VALIDATION_ERROR, `Path is not a directory: ${absolutePath}`, { ...logicContext, requestedPath, resolvedPath: absolutePath });
        }
    
        // Attempt to delete the directory
        if (recursive) {
          // Use fs.rm for recursive deletion (available in Node.js 14.14.0+)
          await fs.rm(absolutePath, { recursive: true, force: true }); // force helps with potential permission issues on subfiles sometimes
          logger.info(`deleteDirectoryLogic: Successfully deleted directory recursively "${absolutePath}"`, { ...logicContext, requestedPath });
        } else {
          // Use fs.rmdir for non-recursive deletion (fails if not empty)
          await fs.rmdir(absolutePath);
          logger.info(`deleteDirectoryLogic: Successfully deleted empty directory "${absolutePath}"`, { ...logicContext, requestedPath });
        }
    
        return {
          message: `Successfully deleted directory: ${absolutePath}${recursive ? ' (recursively)' : ' (empty)'}`,
          deletedPath: absolutePath,
          wasRecursive: recursive,
        };
    
      } catch (error: any) {
        logger.error(`deleteDirectoryLogic: Error deleting directory "${absolutePath}"`, { ...logicContext, requestedPath, error: error.message, code: error.code });
    
        if (error instanceof McpError) {
          throw error; // Re-throw known McpErrors
        }
    
        if (error.code === 'ENOENT') {
          // Should have been caught by stat, but handle defensively
          logger.warning(`deleteDirectoryLogic: Directory not found during delete operation "${absolutePath}"`, { ...logicContext, requestedPath });
          throw new McpError(BaseErrorCode.NOT_FOUND, `Directory not found at path: ${absolutePath}`, { ...logicContext, requestedPath, resolvedPath: absolutePath, originalError: error });
        }
    
        if (error.code === 'ENOTEMPTY' && !recursive) {
          logger.warning(`deleteDirectoryLogic: Directory not empty and recursive=false "${absolutePath}"`, { ...logicContext, requestedPath });
          throw new McpError(BaseErrorCode.VALIDATION_ERROR, `Directory not empty: ${absolutePath}. Use recursive=true to delete non-empty directories.`, { ...logicContext, requestedPath, resolvedPath: absolutePath, originalError: error });
        }
    
        // Handle other potential I/O errors (e.g., permissions)
        throw new McpError(BaseErrorCode.INTERNAL_ERROR, `Failed to delete directory: ${error.message || 'Unknown I/O error'}`, { ...logicContext, requestedPath, resolvedPath: absolutePath, originalError: error });
      }
  • Zod input schema for the delete_directory tool: requires 'path' string and optional 'recursive' boolean (default false).
    export const DeleteDirectoryInputSchema = z.object({
      path: z.string().min(1, 'Path cannot be empty')
        .describe('The path to the directory to delete. Can be relative or absolute.'),
      recursive: z.boolean().default(false)
        .describe('If true, delete the directory and all its contents. If false, only delete if the directory is empty.'),
    });
  • MCP server.tool() registration for 'delete_directory': sets name, description, input shape, and handler that validates input, calls deleteDirectoryLogic, and formats response.
    server.tool(
      'delete_directory', // Tool name
      'Removes a directory. Optionally removes recursively. Accepts relative or absolute paths.', // Description
      DeleteDirectoryInputSchema.shape, // Pass the schema shape
      async (params, extra) => {
        // Validate input using the Zod schema
        const validationResult = DeleteDirectoryInputSchema.safeParse(params);
        if (!validationResult.success) {
          const errorContext = requestContextService.createRequestContext({ operation: 'DeleteDirectoryToolValidation' });
          logger.error('Invalid input parameters for delete_directory tool', { ...errorContext, errors: validationResult.error.errors });
          throw new McpError(BaseErrorCode.VALIDATION_ERROR, `Invalid parameters: ${validationResult.error.errors.map(e => `${e.path.join('.')} - ${e.message}`).join(', ')}`, errorContext);
        }
        const typedParams = validationResult.data; // Use validated data
    
        // Create context for this execution
        const callContext = requestContextService.createRequestContext({ operation: 'DeleteDirectoryToolExecution' });
        logger.info(`Executing 'delete_directory' tool for path: ${typedParams.path}, recursive: ${typedParams.recursive}`, callContext);
    
        // ErrorHandler will catch McpErrors thrown by the logic
        const result = await ErrorHandler.tryCatch(
          () => deleteDirectoryLogic(typedParams, callContext),
          {
            operation: 'deleteDirectoryLogic',
            context: callContext,
            input: sanitization.sanitizeForLogging(typedParams), // Sanitize path
            errorCode: BaseErrorCode.INTERNAL_ERROR
          }
        );
    
        logger.info(`Successfully executed 'delete_directory' for path: ${result.deletedPath}, recursive: ${result.wasRecursive}`, callContext);
    
        // Format the successful response
        return {
          content: [{ type: 'text', text: result.message }],
        };
      }
    );
  • Invocation of registerDeleteDirectoryTool during server tool registration sequence.
    registerDeleteDirectoryTool(server),
  • TypeScript interface for the output of the delete_directory tool.
    export interface DeleteDirectoryOutput {
      message: string;
      deletedPath: string;
      wasRecursive: boolean;
    }
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions the recursive option and path types, but lacks critical details such as permission requirements, whether deletion is irreversible, error handling (e.g., for non-existent paths), or side effects. For a destructive tool with zero annotation coverage, this is a significant gap.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized with two sentences that are front-loaded and efficient. The first sentence states the core action, and the second adds necessary context about recursion and path types, with zero wasted words.

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 the tool's destructive nature, lack of annotations, and no output schema, the description is incomplete. It should address risks (e.g., irreversible deletion), permissions, or error responses to help an agent use it safely. The current description leaves too many behavioral aspects unspecified for a tool that modifies the filesystem.

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 both parameters (path and recursive) with clear descriptions. The description adds minimal value by repeating that paths can be relative or absolute and hinting at recursive behavior, but doesn't provide additional syntax or format details beyond what the schema provides. Baseline 3 is appropriate when the schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with a specific verb ('Removes') and resource ('a directory'), distinguishing it from sibling tools like delete_file (which removes files) and create_directory (which creates directories). The description provides unambiguous action and target.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage through the mention of 'Optionally removes recursively,' suggesting when to use the recursive parameter, but it doesn't explicitly state when to choose this tool over alternatives like delete_file or provide exclusions (e.g., when not to delete system directories). No named alternatives or clear context for tool selection are provided.

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

Related 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/cyanheads/filesystem-mcp-server'

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