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),
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