Skip to main content
Glama

restore-database

Restore Firebird databases from backup files to specified locations, with options to replace existing databases, set page sizes, and monitor progress.

Instructions

Restores a Firebird database from a backup

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
backupPathYesPath to the backup file
targetPathYesPath where the database will be restored
optionsNo

Implementation Reference

  • MCP tool registration including the handler function for 'restore-database'. The handler extracts arguments, calls the low-level restoreDatabase, handles success/error responses, and formats output for MCP.
    // Add restore-database tool
    tools.set("restore-database", {
        name: "restore-database",
        description: "Restores a Firebird database from a backup",
        inputSchema: RestoreDatabaseArgsSchema,
        handler: async (request) => {
            const { backupPath, targetPath, options } = request;
            logger.info(`Executing restore-database tool from: ${backupPath} to: ${targetPath}`);
    
            try {
                const result = await restoreDatabase(backupPath, targetPath, options);
    
                return {
                    content: [{
                        type: "text",
                        text: formatForClaude(result)
                    }]
                };
            } catch (error) {
                const errorResponse = wrapError(error);
                logger.error(`Error restoring database: ${errorResponse.error} [${errorResponse.errorType || 'UNKNOWN'}]`);
    
                return {
                    content: [{
                        type: "text",
                        text: formatForClaude(errorResponse)
                    }]
                };
            }
        }
    });
  • Zod schema defining the input parameters for the restore-database tool, including backupPath, targetPath, and optional restore options.
    export const RestoreDatabaseArgsSchema = z.object({
        backupPath: z.string().min(1).describe("Path to the backup file"),
        targetPath: z.string().min(1).describe("Path where the database will be restored"),
        options: z.object({
            replace: z.boolean().default(false).describe("Whether to replace the target database if it exists"),
            pageSize: z.number().int().min(1024).max(16384).default(4096).describe("Page size for the restored database"),
            verbose: z.boolean().default(false).describe("Whether to show detailed progress")
        }).optional()
    });
  • Core implementation of database restoration using Firebird's gbak or nbackup tools via child_process.spawn, including validation, command construction, and error handling.
    export const restoreDatabase = async (
        backupPath: string,
        targetPath: string,
        options: RestoreOptions = {},
        config = DEFAULT_CONFIG
    ): Promise<RestoreResult> => {
        const startTime = Date.now();
    
        try {
            // Check if Firebird tools are installed
            const toolsCheck = await checkFirebirdTools();
            if (!toolsCheck.installed) {
                throw new FirebirdError(
                    `Firebird client tools are not installed. ${toolsCheck.installInstructions}`,
                    'MISSING_FIREBIRD_TOOLS'
                );
            }
    
            // Check if the backup file exists
            if (!fs.existsSync(backupPath)) {
                throw new FirebirdError(
                    `Backup file not found: ${backupPath}`,
                    'FILE_NOT_FOUND'
                );
            }
    
            // Check if the target database already exists
            if (fs.existsSync(targetPath) && !options.replace) {
                throw new FirebirdError(
                    `Target database already exists: ${targetPath}. Use 'replace: true' to overwrite.`,
                    'FILE_EXISTS'
                );
            }
    
            // Ensure the target directory exists
            const targetDir = path.dirname(targetPath);
            if (!fs.existsSync(targetDir)) {
                fs.mkdirSync(targetDir, { recursive: true });
            }
    
            // Determine which restore tool to use based on the backup file extension
            const ext = path.extname(backupPath).toLowerCase();
            let command: string;
            let args: string[] = [];
    
            // Try to find Firebird bin directory
            const firebirdBinPath = await findFirebirdBinPath();
    
            if (ext === '.fbk' || ext === '.gbk') {
                // GBAK restore
                command = firebirdBinPath ? path.join(firebirdBinPath, 'gbak') : 'gbak';
                args = [
                    '-c',  // Create (restore)
                    '-v',  // Verbose output
                    '-user', config.user || 'SYSDBA',
                    '-password', config.password || 'masterkey'
                ];
    
                // Set page size if specified
                if (options.pageSize) {
                    args.push('-page_size', options.pageSize.toString());
                }
    
                // Add backup path and target database path
                args.push(backupPath, targetPath);
            } else if (ext === '.nbk') {
                // NBACKUP restore
                command = firebirdBinPath ? path.join(firebirdBinPath, 'nbackup') : 'nbackup';
                args = [
                    '-R',  // Restore
                    '-user', config.user || 'SYSDBA',
                    '-password', config.password || 'masterkey'
                ];
    
                // Add target database path and backup path
                args.push(targetPath, backupPath);
            } else {
                throw new FirebirdError(
                    `Unknown backup file format: ${ext}`,
                    'CONFIGURATION_ERROR'
                );
            }
    
            logger.info(`Starting database restore from ${backupPath} to ${targetPath}`);
            if (options.verbose) {
                logger.debug(`Restore command: ${command} ${args.join(' ')}`);
            }
    
            // Execute the restore command
            const result = await executeCommand(command, args, options.verbose);
    
            const duration = Date.now() - startTime;
            logger.info(`Restore completed successfully in ${duration}ms`);
    
            return {
                success: true,
                targetPath,
                duration,
                details: result
            };
        } catch (error: any) {
            const duration = Date.now() - startTime;
            const errorMessage = `Error restoring database: ${error.message || error}`;
            logger.error(errorMessage);
    
            return {
                success: false,
                targetPath,
                duration,
                error: errorMessage,
                details: error.details || ''
            };
        }
    };

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/PuroDelphi/mcpFirebird'

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