Skip to main content
Glama

create_directories

Generate multiple directories at specified paths, including any intermediate folders, using this tool. Simplify file system organization in a few steps.

Instructions

Create multiple specified directories (including intermediate ones).

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathsYesAn array of relative directory paths to create.

Implementation Reference

  • Core handler logic: validates args with Zod, resolves and creates directories recursively using fs.mkdir, handles EEXIST by checking if directory, permission errors, etc., processes multiple paths in parallel with Promise.allSettled, sorts results by input order, returns JSON of results.
    export const handleCreateDirectoriesInternal = async (
      args: unknown,
      deps: CreateDirsDeps,
    ): Promise<McpToolResponse> => {
      let pathsToCreate: string[];
      try {
        // Validate arguments first
        const validatedArgs = parseAndValidateArgs(args);
        pathsToCreate = validatedArgs.paths;
      } catch (error) {
        // If validation fails, re-throw the McpError from parseAndValidateArgs
        if (error instanceof McpError) {
          throw error;
        }
        // Wrap unexpected validation errors
        throw new McpError(
          ErrorCode.InvalidParams,
          `Unexpected error during argument validation: ${error instanceof Error ? error.message : String(error)}`,
        );
      }
    
      // Proceed with validated paths
      const creationPromises = pathsToCreate.map((p) => processSingleDirectoryCreation(p, deps));
      const settledResults = await Promise.allSettled(creationPromises);
    
      const outputResults = processSettledResults(settledResults, pathsToCreate);
    
      // Sort results by original path order for predictability
      const originalIndexMap = new Map(pathsToCreate.map((p, i) => [p.replaceAll('\\', '/'), i]));
      outputResults.sort((a, b) => {
        const indexA = originalIndexMap.get(a.path) ?? Infinity;
        const indexB = originalIndexMap.get(b.path) ?? Infinity;
        return indexA - indexB;
      });
    
      return {
        content: [{ type: 'text', text: JSON.stringify(outputResults, undefined, 2) }],
      };
    };
  • Zod input schema: strict object with non-empty array of relative directory paths.
    export const CreateDirsArgsSchema = z
      .object({
        paths: z
          .array(z.string())
          .min(1, { message: 'Paths array cannot be empty' })
          .describe('An array of relative directory paths to create.'),
      })
      .strict();
  • Tool definition is registered by inclusion in the allToolDefinitions array exported from handlers/index.ts, which aggregates all tools.
    createDirectoriesToolDefinition,
  • Tool definition object exporting the tool name, description, inputSchema reference, and a wrapper handler that injects production dependencies (fs.mkdir, stat, resolvePath, PROJECT_ROOT) before calling the core internal handler.
    export const createDirectoriesToolDefinition = {
      name: 'create_directories',
      description: 'Create multiple specified directories (including intermediate ones).',
      inputSchema: CreateDirsArgsSchema,
      handler: (args: unknown): Promise<McpToolResponse> => {
        // Production handler provides real dependencies
        const productionDeps: CreateDirsDeps = {
          mkdir: fs.mkdir,
          stat: fs.stat,
          resolvePath: resolvePath,
          PROJECT_ROOT: PROJECT_ROOT,
        };
        return handleCreateDirectoriesInternal(args, productionDeps);
      },
    };
  • Key helper: processes single directory creation - resolves path, prevents root creation, mkdir recursive, handles EEXIST specially, other errors.
    async function processSingleDirectoryCreation(
      relativePath: string, // Corrected signature: relativePath first
      deps: CreateDirsDeps, // Corrected signature: deps second
    ): Promise<CreateDirResult> {
      const pathOutput = relativePath.replaceAll('\\', '/'); // Normalize for output consistency
      let targetPath = '';
      try {
        targetPath = await deps.resolvePath(relativePath); // Use deps.resolvePath
        if (targetPath === deps.PROJECT_ROOT) {
          // Use deps.PROJECT_ROOT
          return {
            path: pathOutput,
            success: false,
            error: 'Creating the project root is not allowed.',
            resolvedPath: targetPath,
          };
        }
        await deps.mkdir(targetPath, { recursive: true }); // Use deps.mkdir
        return { path: pathOutput, success: true, resolvedPath: targetPath };
      } catch (error: unknown) {
        if (error && typeof error === 'object' && 'code' in error && error.code === 'EEXIST') {
          // Pass deps to handleEexistError
          return await handleEexistError(targetPath, pathOutput, deps);
        }
        // Pass potential McpError from resolvePath or other errors
        return handleDirectoryCreationError(error, pathOutput, targetPath);
      }
    }
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. It mentions creating directories 'including intermediate ones,' which adds some behavioral context (e.g., recursive creation). However, it lacks details on permissions, error handling (e.g., if paths exist), side effects, or response format, leaving gaps for a mutation tool.

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 waste. It front-loads the core action ('Create multiple specified directories') and adds a clarifying detail ('including intermediate ones') without unnecessary elaboration, making it easy to parse.

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 complexity (a mutation operation with no annotations and no output schema), the description is incomplete. It doesn't cover behavioral aspects like error conditions, permissions needed, or what happens on success/failure. For a tool that modifies the filesystem, more context is needed to ensure safe and correct usage.

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%, with the parameter 'paths' documented as 'An array of relative directory paths to create.' The description adds minimal value beyond this, only implying the array handles multiple paths. Since the schema does the heavy lifting, the baseline score of 3 is appropriate.

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 ('Create') and resource ('multiple specified directories'), specifying it includes intermediate directories. It distinguishes from siblings like 'list_files' or 'delete_items' by focusing on directory creation, though it doesn't explicitly contrast with similar tools (e.g., 'write_content' might also create directories).

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 prerequisites (e.g., permissions), when not to use it (e.g., for single directories vs. multiple), or refer to sibling tools like 'chmod_items' for post-creation adjustments. Usage is implied by the action but not contextualized.

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/SylphxAI/filesystem-mcp'

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