Skip to main content
Glama

backup_restore

Restore Redis data from backup files to recover databases after data loss or corruption. Specify filename and optional path, with option to flush database before restoration.

Instructions

从备份恢复 Redis 数据

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filenameYes备份文件名
pathNo备份路径(可选)
flushBeforeRestoreNo恢复前是否清空数据库(可选,默认为 false)

Implementation Reference

  • The primary MCP tool handler for 'backup_restore'. Ensures Redis connection, initializes backup service if needed, constructs restore options from args, calls the underlying restore method, and returns formatted MCP response.
    private async handleBackupRestore(args: any) {
      this.ensureRedisConnection();
      if (!this.backupService) {
        throw new McpError(
          ErrorCode.InternalError,
          'Backup service not initialized'
        );
      }
      
      const options: RedisRestoreOptions = {
        filename: args.filename,
        path: args.path,
        flushBeforeRestore: args.flushBeforeRestore
      };
      
      const result = await this.backupService.restore(options);
      
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(result, null, 2)
          }
        ]
      };
    }
  • Input schema definition for the backup_restore tool, registered in the listTools handler response.
    {
      name: 'backup_restore',
      description: '从备份恢复 Redis 数据',
      inputSchema: {
        type: 'object',
        properties: {
          filename: { type: 'string', description: '备份文件名' },
          path: { type: 'string', description: '备份路径(可选)' },
          flushBeforeRestore: { 
            type: 'boolean', 
            description: '恢复前是否清空数据库(可选,默认为 false)' 
          }
        },
        required: ['filename']
      }
    }
  • Tool dispatch registration in the CallToolRequestSchema switch statement.
    case 'backup_restore':
      return await this.handleBackupRestore(args);
  • Core restore implementation that reads backup JSON, optionally flushes DB, iterates over keys by type (string, hash, list, set, zset), restores data using RedisService methods, and sets TTLs.
    async restore(options: RedisRestoreOptions): Promise<RedisOperationResult<string>> {
      try {
        const { filename, path: restorePath = './backups', flushBeforeRestore = false } = options;
        const fullPath = path.join(restorePath, filename);
    
        // 检查文件是否存在
        if (!fs.existsSync(fullPath)) {
          return {
            success: false,
            error: `Backup file not found: ${fullPath}`
          };
        }
    
        // 读取备份文件
        const backupContent = fs.readFileSync(fullPath, 'utf8');
        const backupData = JSON.parse(backupContent);
    
        // 如果需要,先清空数据库
        if (flushBeforeRestore) {
          const flushResult = await this.redisService.flushdb();
          if (!flushResult.success) {
            return {
              success: false,
              error: `Failed to flush database before restore: ${flushResult.error}`
            };
          }
        }
    
        // 恢复每个键
        for (const [key, data] of Object.entries<any>(backupData)) {
          const { type, ttl, value } = data;
    
          // 根据类型恢复数据
          switch (type) {
            case 'string': {
              await this.redisService.set(key, value);
              break;
            }
            case 'hash': {
              const fields = Object.entries(value).map(([field, val]) => ({
                field,
                value: val as string
              }));
              await this.redisService.hmset(key, fields);
              break;
            }
            case 'list': {
              // 先删除可能存在的键,以避免追加到现有列表
              await this.redisService.del(key);
              if (Array.isArray(value) && value.length > 0) {
                await this.redisService.rpush(key, value);
              }
              break;
            }
            case 'set': {
              if (Array.isArray(value) && value.length > 0) {
                await this.redisService.sadd(key, value);
              }
              break;
            }
            case 'zset': {
              if (Array.isArray(value) && value.length > 0) {
                const members = value.map((item: any) => ({
                  member: item.value,
                  score: item.score
                }));
                await this.redisService.zadd(key, members);
              }
              break;
            }
          }
    
          // 设置过期时间(如果有)
          if (ttl > 0) {
            await this.redisService.expire(key, ttl);
          }
        }
    
        return {
          success: true,
          data: `Restore completed successfully from ${fullPath}`
        };
      } catch (error) {
        return {
          success: false,
          error: `Restore failed: ${error instanceof Error ? error.message : String(error)}`
        };
      }
    }
Behavior2/5

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

No annotations are provided, so the description carries full burden. '恢复 Redis 数据' implies a write/mutation operation, but it doesn't disclose critical behaviors: whether it overwrites existing data, requires specific permissions, has side effects (e.g., downtime), or error handling. For a mutation tool with zero annotation coverage, this is a significant gap.

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 in Chinese ('从备份恢复 Redis 数据'), which directly states the purpose without waste. It's appropriately sized and front-loaded, earning full marks for conciseness.

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 complexity (a mutation tool restoring data), no annotations, no output schema, and incomplete behavioral disclosure, the description is inadequate. It should cover more: what happens to existing data, success/error responses, or dependencies (e.g., needing a backup file). The current description leaves too many gaps for safe use.

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 already documents all parameters (filename, path, flushBeforeRestore) with descriptions. The tool description adds no additional meaning beyond the schema, such as format examples or constraints. Baseline 3 is appropriate when schema does the heavy lifting.

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 '从备份恢复 Redis 数据' clearly states the action (恢复/restore) and resource (Redis 数据/Redis data). It distinguishes from siblings like backup_create (create vs restore) but doesn't specify scope like which database or cluster, keeping it at 4 rather than 5.

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?

No explicit guidance on when to use this tool versus alternatives. It doesn't mention prerequisites (e.g., need for existing backup files, connection state), exclusions, or comparisons with siblings like db_flush or key operations. The description alone implies usage but lacks actionable context.

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

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/pickstar-2002/redis-mcp'

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