Skip to main content
Glama

MCP File Editor Server

by pwilkin
create_file.ts2.64 kB
import { UserError } from 'fastmcp'; import * as fs from 'fs'; import * as path from 'path'; import { validateAbsolutePath } from './utils.js'; /** * Creates a new file with the specified content at the given path. * If the file already exists, the function will fail and not overwrite it. * * @param file_path - The relative path (from the project root) where the file should be created * @param contents - The text content to write into the new file * @returns A success message indicating the file was created * @throws UserError if the file already exists or if there's an error creating directories or the file */ export function createFile(file_path: string, contents: string): string { // Convert relative path to absolute path const absolutePath = path.resolve(file_path); // Validate that the path is absolute (after resolution) validateAbsolutePath(absolutePath, 'file_path'); // Check if the file already exists if (fs.existsSync(absolutePath)) { const stats = fs.statSync(absolutePath); if (stats.isFile()) { throw new UserError( `File already exists at "${absolutePath}". The create_file tool does not overwrite existing files. ` + `If you want to modify an existing file, please use one of the file editing tools instead.` ); } else { throw new UserError( `A directory already exists at "${absolutePath}". Cannot create a file at this location.` ); } } try { // Get the directory path const dirPath = path.dirname(absolutePath); // Create directories if they don't exist (recursively) if (!fs.existsSync(dirPath)) { fs.mkdirSync(dirPath, { recursive: true }); } // Create the file with the provided content fs.writeFileSync(absolutePath, contents, 'utf-8'); return `Successfully created file at "${absolutePath}"`; } catch (error: any) { if (error instanceof UserError) { throw error; } // Handle specific file system errors if (error.code === 'EACCES') { throw new UserError( `Permission denied: Cannot create file at "${absolutePath}". Please check file and directory permissions.` ); } else if (error.code === 'ENOSPC') { throw new UserError( `No space left on device: Cannot create file at "${absolutePath}".` ); } else if (error.code === 'EROFS') { throw new UserError( `Read-only file system: Cannot create file at "${absolutePath}".` ); } else { throw new UserError( `Error creating file at "${absolutePath}": ${error.message}` ); } } }

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/pwilkin/mcp-file-edit'

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