Skip to main content
Glama

backup_create

Create Redis database backups with customizable filename, path, and key pattern filters to protect your data.

Instructions

创建 Redis 数据备份

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filenameNo备份文件名(可选)
pathNo备份路径(可选)
includePatternsNo包含的键模式数组(可选,默认为 ["*"])
excludePatternsNo排除的键模式数组(可选)

Implementation Reference

  • The MCP tool handler method for 'backup_create' that ensures Redis connection, prepares backup options from args, delegates to RedisBackupService.backup(), and formats the response as MCP content.
    private async handleBackupCreate(args: any) {
      this.ensureRedisConnection();
      if (!this.backupService) {
        throw new McpError(
          ErrorCode.InternalError,
          'Backup service not initialized'
        );
      }
      
      const options: RedisBackupOptions = {
        filename: args.filename,
        path: args.path,
        includePatterns: args.includePatterns,
        excludePatterns: args.excludePatterns
      };
      
      const result = await this.backupService.backup(options);
      
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(result, null, 2)
          }
        ]
      };
    }
  • Tool metadata and input schema definition for 'backup_create' returned by ListToolsRequestSchema handler.
    {
      name: 'backup_create',
      description: '创建 Redis 数据备份',
      inputSchema: {
        type: 'object',
        properties: {
          filename: { type: 'string', description: '备份文件名(可选)' },
          path: { type: 'string', description: '备份路径(可选)' },
          includePatterns: { 
            type: 'array', 
            items: { type: 'string' },
            description: '包含的键模式数组(可选,默认为 ["*"])' 
          },
          excludePatterns: { 
            type: 'array', 
            items: { type: 'string' },
            description: '排除的键模式数组(可选)' 
          }
        }
      }
    },
  • Registration/dispatch case in the CallToolRequestSchema switch statement that maps 'backup_create' tool calls to the handler method.
    case 'backup_create':
      return await this.handleBackupCreate(args);
  • Core helper method implementing backup logic: processes include/exclude patterns, fetches keys, retrieves data and TTL by Redis data type (string/hash/list/set/zset), saves structured data to timestamped JSON file in backups directory.
    async backup(options: RedisBackupOptions = {}): Promise<RedisOperationResult<string>> {
      try {
        // 设置默认选项
        const filename = options.filename || `redis-backup-${new Date().toISOString().replace(/[:.]/g, '-')}.json`;
        const backupPath = options.path || './backups';
        const includePatterns = options.includePatterns || ['*'];
        const excludePatterns = options.excludePatterns || [];
    
        // 确保备份目录存在
        if (!fs.existsSync(backupPath)) {
          fs.mkdirSync(backupPath, { recursive: true });
        }
    
        const fullPath = path.join(backupPath, filename);
        const backupData: Record<string, any> = {};
    
        // 处理包含的模式
        for (const pattern of includePatterns) {
          // 获取匹配的键
          const keysResult = await this.redisService.keys(pattern);
          if (!keysResult.success || !keysResult.data) {
            continue;
          }
    
          const keys = keysResult.data;
          
          // 过滤排除的键
          const filteredKeys = keys.filter(key => {
            return !excludePatterns.some(excludePattern => {
              // 支持简单的通配符匹配
              const regexPattern = excludePattern
                .replace(/\*/g, '.*')
                .replace(/\?/g, '.');
              return new RegExp(`^${regexPattern}$`).test(key);
            });
          });
    
          // 处理每个键
          for (const key of filteredKeys) {
            const typeResult = await this.redisService.type(key);
            if (!typeResult.success || !typeResult.data) {
              continue;
            }
    
            const type = typeResult.data;
            const ttlResult = await this.redisService.ttl(key);
            const ttl = ttlResult.success ? ttlResult.data : -1;
    
            // 根据类型获取数据
            switch (type) {
              case 'string': {
                const valueResult = await this.redisService.get(key);
                if (valueResult.success && valueResult.data !== null) {
                  backupData[key] = {
                    type,
                    ttl,
                    value: valueResult.data
                  };
                }
                break;
              }
              case 'hash': {
                const valueResult = await this.redisService.hgetall(key);
                if (valueResult.success && valueResult.data) {
                  backupData[key] = {
                    type,
                    ttl,
                    value: valueResult.data
                  };
                }
                break;
              }
              case 'list': {
                const valueResult = await this.redisService.lrange(key, 0, -1);
                if (valueResult.success && valueResult.data) {
                  backupData[key] = {
                    type,
                    ttl,
                    value: valueResult.data
                  };
                }
                break;
              }
              case 'set': {
                const valueResult = await this.redisService.smembers(key);
                if (valueResult.success && valueResult.data) {
                  backupData[key] = {
                    type,
                    ttl,
                    value: valueResult.data
                  };
                }
                break;
              }
              case 'zset': {
                const valueResult = await this.redisService.zrange(key, 0, -1, true);
                if (valueResult.success && valueResult.data) {
                  backupData[key] = {
                    type,
                    ttl,
                    value: valueResult.data
                  };
                }
                break;
              }
            }
          }
        }
    
        // 写入备份文件
        fs.writeFileSync(fullPath, JSON.stringify(backupData, null, 2));
    
        return {
          success: true,
          data: `Backup completed successfully. Saved to ${fullPath}`
        };
      } catch (error) {
        return {
          success: false,
          error: `Backup 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. '创建' implies a write operation that likely modifies system state, but it doesn't disclose critical behaviors: whether it locks the database, requires admin permissions, has rate limits, or what happens on failure. For a backup tool with zero annotation coverage, this is inadequate.

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 phrase in Chinese that directly states the tool's purpose. There's zero wasted text, and it's appropriately sized for a simple backup creation tool. It's front-loaded with the core action.

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 no annotations, no output schema, and a backup creation tool (which implies system mutation and potential side effects), the description is incomplete. It doesn't explain what the tool returns, error conditions, or behavioral constraints. The agent lacks sufficient context to use this tool safely and effectively.

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%, with all 4 parameters documented in the schema. The description adds no parameter-specific information beyond the tool's general purpose. According to rules, when coverage is high (>80%), baseline is 3 even with no param info in description.

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 (create) and resource (Redis data backup) in Chinese. It distinguishes from sibling tools like backup_restore by specifying creation rather than restoration. However, it doesn't specify what type of backup (full/incremental) or format, 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?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention prerequisites (e.g., Redis connection), compare with other backup methods, or specify scenarios like before maintenance. With sibling tools like connect_redis available, this lack of context is a significant gap.

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