Skip to main content
Glama
MausRundung

Project Explorer MCP Server

by MausRundung

delete_file

Remove files or directories from project structures. Use with caution as deletions are permanent and cannot be undone. Supports recursive deletion of non-empty directories when explicitly enabled.

Instructions

Delete a file or directory. Use with extreme caution as this operation cannot be undone. When deleting directories, all contents will be permanently removed. The recursive option must be explicitly set to true to delete non-empty directories. Only works within allowed directories.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesPath to the file or directory to delete
recursiveNoSet to true to delete directories and their contents recursively. Required for non-empty directories.
forceNoSet to true to force deletion even if file is read-only. Use with caution.

Implementation Reference

  • The main handler function that executes the delete_file tool logic, including input validation, path safety checks, recursive directory deletion, force options, and detailed success/error responses.
    export async function handleDeleteFile(args: any, allowedDirectories: string[]) {
      const { path: targetPath, recursive = false, force = false } = args;
    
      if (!targetPath) {
        throw new McpError(ErrorCode.InvalidParams, "Path is required");
      }
    
      // Resolve to absolute path
      const resolvedPath = path.resolve(targetPath);
    
      // Check if path is within allowed directories
      const isPathAllowed = allowedDirectories.some(dir => {
        const normalizedDir = path.resolve(dir).replace(/\\/g, '/');
        const normalizedPath = resolvedPath.replace(/\\/g, '/');
        return normalizedPath === normalizedDir || normalizedPath.startsWith(normalizedDir + '/');
      });
    
      if (!isPathAllowed) {
        throw new McpError(ErrorCode.InvalidParams, `Path "${resolvedPath}" is not within allowed directories`);
      }
    
      try {
        // Check if path exists
        if (!fs.existsSync(resolvedPath)) {
          throw new McpError(ErrorCode.InvalidParams, `Path "${resolvedPath}" does not exist`);
        }
    
        // Get file stats to determine if it's a file or directory
        const stats = fs.statSync(resolvedPath);
        const isDirectory = stats.isDirectory();
    
        if (isDirectory) {
          // Check if directory is empty
          const contents = fs.readdirSync(resolvedPath);
          const isEmpty = contents.length === 0;
    
          if (!isEmpty && !recursive) {
            throw new McpError(
              ErrorCode.InvalidParams, 
              `Directory "${resolvedPath}" is not empty. Set recursive=true to delete directory and all its contents.`
            );
          }
    
          // Delete directory
          if (recursive) {
            fs.rmSync(resolvedPath, { recursive: true, force: force });
          } else {
            fs.rmdirSync(resolvedPath);
          }
    
          const message = `# Directory Deletion Successful\n\n✅ Successfully deleted directory "${targetPath}"${recursive ? ' and all its contents' : ''}\n\n**Details:**\n- Path: ${resolvedPath}\n- Type: Directory\n- Recursive: ${recursive ? 'Yes' : 'No'}\n- Force: ${force ? 'Yes' : 'No'}`;
          
          return {
            content: [
              {
                type: "text",
                text: message
              }
            ]
          };
    
        } else {
          // Delete file
          if (force) {
            // Remove read-only attribute if forcing
            try {
              fs.chmodSync(resolvedPath, 0o666);
            } catch (chmodError) {
              // Ignore chmod errors, proceed with deletion
            }
          }
    
          fs.unlinkSync(resolvedPath);
    
          const message = `# File Deletion Successful\n\n✅ Successfully deleted file "${targetPath}"\n\n**Details:**\n- Path: ${resolvedPath}\n- Type: File\n- Force: ${force ? 'Yes' : 'No'}`;
          
          return {
            content: [
              {
                type: "text",
                text: message
              }
            ]
          };
        }
    
      } catch (error: any) {
        if (error instanceof McpError) {
          throw error;
        }
    
        // Provide more specific error messages
        let errorMessage = `Failed to delete "${targetPath}": ${error.message}`;
        
        if (error.code === 'ENOTEMPTY') {
          errorMessage = `Directory "${targetPath}" is not empty. Use recursive=true to delete directory and contents.`;
        } else if (error.code === 'EACCES' || error.code === 'EPERM') {
          errorMessage = `Permission denied when trying to delete "${targetPath}". Try using force=true or check file permissions.`;
        } else if (error.code === 'EBUSY') {
          errorMessage = `File "${targetPath}" is currently in use and cannot be deleted.`;
        }
        
        throw new McpError(ErrorCode.InternalError, errorMessage);
      }
    }
  • The tool definition object containing the name, description, and inputSchema for parameter validation of the delete_file tool.
    export const deleteFileTool = {
      name: "delete_file",
      description: "Delete a file or directory. Use with extreme caution as this operation cannot be undone. When deleting directories, all contents will be permanently removed. The recursive option must be explicitly set to true to delete non-empty directories. Only works within allowed directories.",
      inputSchema: {
        type: "object",
        properties: {
          path: {
            type: "string",
            description: "Path to the file or directory to delete"
          },
          recursive: {
            type: "boolean",
            description: "Set to true to delete directories and their contents recursively. Required for non-empty directories.",
            default: false
          },
          force: {
            type: "boolean", 
            description: "Set to true to force deletion even if file is read-only. Use with caution.",
            default: false
          }
        },
        required: ["path"],
        additionalProperties: false
      }
    };
  • src/index.ts:33-44 (registration)
    Registration of the deleteFileTool in the MCP server's ListToolsRequestHandler, making it discoverable by clients.
    server.setRequestHandler(ListToolsRequestSchema, async () => {
      return {
        tools: [
          exploreProjectTool,
          listAllowedTool,
          searchTool,
          renameFileTool,
          deleteFileTool,
          checkOutdatedTool
        ]
      };
    });
  • src/index.ts:65-67 (registration)
    Routing of the 'delete_file' tool calls to the handleDeleteFile handler in the MCP server's CallToolRequestHandler.
    case "delete_file":
      return await handleDeleteFile(args, ALLOWED_DIRECTORIES);
  • src/index.ts:16-16 (registration)
    Import of the deleteFileTool definition and handleDeleteFile function from the delete-file module.
    import { deleteFileTool, handleDeleteFile } from './delete-file.js';
Behavior5/5

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

With no annotations provided, the description carries the full burden and excels by disclosing critical behavioral traits: irreversible nature ('cannot be undone'), destructive scope ('all contents will be permanently removed'), recursive requirements, and directory restrictions. It adds significant value beyond what the input schema implies.

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 appropriately sized and front-loaded, with each sentence earning its place: the first states the purpose, the second warns of irreversibility, the third explains directory behavior, the fourth specifies the recursive option, and the fifth adds a constraint. No wasted words.

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

Completeness4/5

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

Given the high complexity (destructive operation) and no annotations or output schema, the description is nearly complete. It covers purpose, risks, behavioral details, and constraints, but could benefit from mentioning error cases or confirmation prompts, though not strictly required.

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 baseline is 3. The description does not add specific parameter details beyond what the schema provides (e.g., it mentions 'recursive option' but doesn't explain it further). It compensates slightly by contextualizing parameters within behavioral warnings.

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 specific action ('Delete a file or directory') and distinguishes it from siblings like 'rename_file' or 'search_files' by focusing on permanent removal. It goes beyond the tool name by specifying the resource type (file or directory).

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

Usage Guidelines4/5

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

The description provides clear context for when to use it ('Delete a file or directory') and includes explicit warnings ('Use with extreme caution'), but it does not mention when to use alternatives like 'rename_file' or 'list_allowed_directories' for safer operations. It does specify constraints like 'Only works within allowed directories'.

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/MausRundung/mcp-explorer'

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