Skip to main content
Glama

create_directory

Use this tool to create directories, including parent directories if needed, using relative or absolute paths. Simplifies filesystem organization with optional parent directory creation.

Instructions

Creates a directory. Optionally creates parent directories. Accepts relative or absolute paths.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
create_parentsNoIf true, create any necessary parent directories that don't exist. If false, fail if a parent directory is missing.
pathYesThe path to the directory to create. Can be relative or absolute.

Implementation Reference

  • Core handler function that implements the 'create_directory' tool logic, resolving paths, checking existence, and creating directories with fs.mkdir.
    export const createDirectoryLogic = async (input: CreateDirectoryInput, context: RequestContext): Promise<CreateDirectoryOutput> => {
      const { path: requestedPath, create_parents } = input;
      const logicContext = { ...context, tool: 'createDirectoryLogic', create_parents };
      logger.debug(`createDirectoryLogic: Received request to create directory "${requestedPath}"`, logicContext);
    
      // Resolve the path
      const absolutePath = serverState.resolvePath(requestedPath, context);
      logger.debug(`createDirectoryLogic: Resolved path to "${absolutePath}"`, { ...logicContext, requestedPath });
    
      try {
        // Check if path already exists
        try {
          const stats = await fs.stat(absolutePath);
          if (stats.isDirectory()) {
            logger.info(`createDirectoryLogic: Directory already exists at "${absolutePath}"`, { ...logicContext, requestedPath });
            // Directory already exists, consider this a success (idempotent)
            return {
              message: `Directory already exists: ${absolutePath}`,
              createdPath: absolutePath,
              parentsCreated: false, // No parents needed to be created now
            };
          } else {
            // Path exists but is not a directory (e.g., a file)
            logger.error(`createDirectoryLogic: Path exists but is not a directory "${absolutePath}"`, { ...logicContext, requestedPath });
            throw new McpError(BaseErrorCode.VALIDATION_ERROR, `Path already exists but is not a directory: ${absolutePath}`, { ...logicContext, requestedPath, resolvedPath: absolutePath });
          }
        } catch (statError: any) {
          if (statError.code !== 'ENOENT') {
            // If error is something other than "Not Found", re-throw it
            throw statError;
          }
          // Path does not exist, proceed with creation
          logger.debug(`createDirectoryLogic: Path does not exist, proceeding with creation "${absolutePath}"`, { ...logicContext, requestedPath });
        }
    
        // Attempt to create the directory
        await fs.mkdir(absolutePath, { recursive: create_parents });
        logger.info(`createDirectoryLogic: Successfully created directory "${absolutePath}" (parents: ${create_parents})`, { ...logicContext, requestedPath });
    
        return {
          message: `Successfully created directory: ${absolutePath}${create_parents ? ' (including parents if needed)' : ''}`,
          createdPath: absolutePath,
          parentsCreated: create_parents, // Reflects the *option* enabled, not necessarily if they *were* created
        };
    
      } catch (error: any) {
        logger.error(`createDirectoryLogic: Error creating directory "${absolutePath}"`, { ...logicContext, requestedPath, error: error.message, code: error.code });
    
        if (error instanceof McpError) {
          throw error; // Re-throw known McpErrors
        }
    
        // Handle potential I/O errors (e.g., permissions, invalid path components)
        throw new McpError(BaseErrorCode.INTERNAL_ERROR, `Failed to create directory: ${error.message || 'Unknown I/O error'}`, { ...logicContext, requestedPath, resolvedPath: absolutePath, originalError: error });
      }
    };
  • Zod schema defining the input parameters for the 'create_directory' tool: path (string) and create_parents (boolean).
    export const CreateDirectoryInputSchema = z.object({
      path: z.string().min(1, 'Path cannot be empty')
        .describe('The path to the directory to create. Can be relative or absolute.'),
      create_parents: z.boolean().default(true)
        .describe('If true, create any necessary parent directories that don\'t exist. If false, fail if a parent directory is missing.'),
    });
  • Registration function that calls server.tool('create_directory', ...) with input schema, description, and a wrapper handler that validates input and delegates to createDirectoryLogic.
    export const registerCreateDirectoryTool = async (server: McpServer): Promise<void> => {
      const registrationContext = requestContextService.createRequestContext({ operation: 'RegisterCreateDirectoryTool' });
      logger.info("Attempting to register 'create_directory' tool", registrationContext);
    
      await ErrorHandler.tryCatch(
        async () => {
          server.tool(
            'create_directory', // Tool name
            'Creates a directory. Optionally creates parent directories. Accepts relative or absolute paths.', // Description
            CreateDirectoryInputSchema.shape, // Pass the schema shape
            async (params, extra) => {
              // Validate input using the Zod schema
              const validationResult = CreateDirectoryInputSchema.safeParse(params);
              if (!validationResult.success) {
                const errorContext = requestContextService.createRequestContext({ operation: 'CreateDirectoryToolValidation' });
                logger.error('Invalid input parameters for create_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: 'CreateDirectoryToolExecution' });
              logger.info(`Executing 'create_directory' tool for path: ${typedParams.path}, create_parents: ${typedParams.create_parents}`, callContext);
    
              // ErrorHandler will catch McpErrors thrown by the logic
              const result = await ErrorHandler.tryCatch(
                () => createDirectoryLogic(typedParams, callContext),
                {
                  operation: 'createDirectoryLogic',
                  context: callContext,
                  input: sanitization.sanitizeForLogging(typedParams), // Sanitize path
                  errorCode: BaseErrorCode.INTERNAL_ERROR
                }
              );
    
              logger.info(`Successfully executed 'create_directory' for path: ${result.createdPath}, parentsCreated: ${result.parentsCreated}`, callContext);
    
              // Format the successful response
              return {
                content: [{ type: 'text', text: result.message }],
              };
            }
          );
          logger.info("'create_directory' tool registered successfully", registrationContext);
        },
        {
          operation: 'registerCreateDirectoryTool',
          context: registrationContext,
          errorCode: BaseErrorCode.CONFIGURATION_ERROR,
          critical: true
        }
      );
    };
  • Top-level call to register the 'create_directory' tool during server initialization.
    registerCreateDirectoryTool(server),
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions that the tool can fail if parent directories are missing (when create_parents is false) and supports relative/absolute paths, but doesn't cover critical aspects like permissions needed, error handling, or whether it overwrites existing directories. For a mutation tool with zero annotation coverage, this leaves significant gaps.

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 extremely concise with three short sentences that each add value: the core action, the parent directory feature, and path flexibility. There is no wasted text, and it's front-loaded with the primary 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?

For a mutation tool with no annotations and no output schema, the description is incomplete. It doesn't explain what happens on success (e.g., returns the created path), error conditions beyond missing parents, or permissions required. Given the complexity of filesystem operations and lack of structured safety hints, more behavioral context is needed.

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 fully documents both parameters. The description adds minimal value by restating that paths can be relative or absolute (already in schema) and hinting at parent directory creation (implied by create_parents). It doesn't provide additional syntax, format, or usage details beyond what the schema offers.

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 ('Creates a directory') and distinguishes it from siblings like 'delete_directory' or 'list_files' by focusing on creation. It also adds nuance about parent directory creation, which further differentiates it from simple file operations.

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 like 'write_file' for creating files or 'set_filesystem_default' for configuration. It mentions optional parent directory creation but doesn't explain when to enable or disable this feature in practice.

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