Skip to main content
Glama
Heht571
by Heht571

backup_critical_files

Backup critical system configuration files from remote servers via SSH to protect against data loss or corruption.

Instructions

备份重要系统配置文件

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
hostnameYes
usernameYes
passwordNo
portNo
filesNo
backup_dirNo/tmp/backup
timeoutNo

Implementation Reference

  • Primary handler implementation for the backup_critical_files tool. Connects to remote server via SSH, creates a timestamped backup directory, and copies specified critical files (default: /etc/passwd, /etc/shadow, etc.) to backups with .bak extension.
    def backup_critical_files(
        hostname: str,
        username: str,
        password: str = "",
        port: int = 22,
        files: list[str] = ["/etc/passwd", "/etc/shadow", "/etc/fstab", "/etc/hosts"],
        backup_dir: str = "/tmp/backup",
        timeout: int = 60
    ) -> dict:
        """备份重要系统配置文件"""
        result = {"status": "unknown", "backups": [], "error": ""}
    
        try:
            with SSHManager(hostname, username, password, port, timeout) as ssh:
                # 创建备份目录
                mkdir_command = f"mkdir -p {backup_dir}"
                stdin, stdout, stderr = ssh.exec_command(mkdir_command, timeout=timeout)
    
                # 获取当前时间作为备份标识
                date_command = "date +%Y%m%d_%H%M%S"
                stdin, stdout, stderr = ssh.exec_command(date_command, timeout=timeout)
                date_string = stdout.read().decode().strip()
    
                backups = []
                for file_path in files:
                    # 提取文件名
                    file_name = file_path.split("/")[-1]
                    backup_path = f"{backup_dir}/{file_name}.{date_string}.bak"
    
                    # 检查文件是否存在
                    check_command = f"[ -f {file_path} ] && echo 'exists' || echo 'not found'"
                    stdin, stdout, stderr = ssh.exec_command(check_command, timeout=timeout)
                    file_exists = stdout.read().decode().strip() == "exists"
    
                    if file_exists:
                        # 复制文件
                        copy_command = f"cp {file_path} {backup_path}"
                        stdin, stdout, stderr = ssh.exec_command(copy_command, timeout=timeout)
    
                        # 检查备份是否成功
                        check_backup = f"[ -f {backup_path} ] && echo 'success' || echo 'failed'"
                        stdin, stdout, stderr = ssh.exec_command(check_backup, timeout=timeout)
                        backup_status = stdout.read().decode().strip() == "success"
    
                        backups.append({
                            "original_file": file_path,
                            "backup_file": backup_path,
                            "status": "success" if backup_status else "failed"
                        })
                    else:
                        backups.append({
                            "original_file": file_path,
                            "backup_file": "",
                            "status": "file not found"
                        })
    
                result["backups"] = backups
                result["status"] = "success"
    
        except Exception as e:
            result["status"] = "error"
            result["error"] = str(e)
    
        return result
  • SSE variant handler for backup_critical_files. Similar to primary but uses files_to_backup param and simpler .bak naming without timestamp.
    def backup_critical_files(
        hostname: str,
        username: str,
        password: str = "",
        port: int = 22,
        backup_dir: str = "/tmp/backup",
        files_to_backup: list[str] = ["/etc/passwd", "/etc/shadow", "/etc/ssh/sshd_config"],
        timeout: int = 30
    ) -> dict:
        """备份关键系统文件"""
        result = {"status": "unknown", "backup_results": [], "error": ""}
    
        try:
            with SSHManager(hostname, username, password, port, timeout) as ssh:
                # 创建备份目录
                stdin, stdout, stderr = ssh.exec_command(f"mkdir -p {backup_dir}", timeout=timeout)
                error = stderr.read().decode().strip()
                if error:
                    result["status"] = "error"
                    result["error"] = f"创建备份目录失败: {error}"
                    return result
    
                backup_results = []
                for file_path in files_to_backup:
                    # 检查文件是否存在
                    stdin, stdout, stderr = ssh.exec_command(f"ls {file_path}", timeout=timeout)
                    error = stderr.read().decode().strip()
                    if error:
                        backup_results.append({
                            "file": file_path,
                            "status": "error",
                            "message": f"文件不存在: {error}"
                        })
                        continue
    
                    # 获取文件名
                    file_name = file_path.split('/')[-1]
                    backup_path = f"{backup_dir}/{file_name}.bak"
    
                    # 备份文件
                    stdin, stdout, stderr = ssh.exec_command(f"cp {file_path} {backup_path}", timeout=timeout)
                    error = stderr.read().decode().strip()
                    if error:
                        backup_results.append({
                            "file": file_path,
                            "status": "error",
                            "message": f"备份失败: {error}"
                        })
                    else:
                        backup_results.append({
                            "file": file_path,
                            "status": "success",
                            "backup_path": backup_path
                        })
    
                result["backup_results"] = backup_results
                result["status"] = "success"
    
        except Exception as e:
            result["status"] = "error"
            result["error"] = str(e)
    
        return result
  • Tool schema definition including parameters and defaults for backup_critical_files.
    {"name": "backup_critical_files", "description": "备份重要系统配置文件", "parameters": [
        {"name": "hostname", "type": "str", "default": None},
        {"name": "username", "type": "str", "default": None},
        {"name": "password", "type": "str", "default": ""},
        {"name": "port", "type": "int", "default": 22},
        {"name": "files", "type": "list[str]", "default": ["/etc/passwd", "/etc/shadow", "/etc/fstab", "/etc/hosts"]},
        {"name": "backup_dir", "type": "str", "default": "/tmp/backup"},
        {"name": "timeout", "type": "int", "default": 60}
    ]},
  • Registration of backup_critical_files in the MCP tools dictionary for dynamic registration using mcp.tool() decorator.
    'backup_critical_files': backup_critical_files,
  • Tool dispatch registration in SSE server: handles call to backup_critical_files by parsing arguments and invoking the handler.
    elif name == "backup_critical_files":
        required_args = ["hostname", "username"]
        for arg in required_args:
            if arg not in arguments:
                raise ValueError(f"Missing required argument '{arg}'")
    
        result = backup_critical_files(
            hostname=arguments["hostname"],
            username=arguments["username"],
            password=arguments.get("password", ""),
            port=arguments.get("port", 22),
            backup_dir=arguments.get("backup_dir", "/tmp/backup"),
            files_to_backup=arguments.get("files_to_backup", ["/etc/passwd", "/etc/shadow", "/etc/ssh/sshd_config"]),
            timeout=arguments.get("timeout", 30)
        )
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. '备份' (backup) implies a read-only copy operation, but the description doesn't specify whether this requires special permissions, what happens if files don't exist, whether the operation is idempotent, or what the expected output format is. It mentions '重要系统配置文件' (important system configuration files) but doesn't define importance criteria or default behavior.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is extremely concise - a single Chinese phrase. While this is efficient, it's arguably under-specified rather than appropriately concise. There's no wasted language, but also no structural elements like separation of purpose from usage guidelines. The front-loading is perfect since there's only one element to front-load.

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?

For a 7-parameter tool with no annotations and no output schema, the description is severely incomplete. It doesn't explain the remote SSH nature of the operation (implied by parameters), doesn't describe what constitutes a successful backup, doesn't mention error conditions, and provides no information about return values or side effects. The description leaves critical gaps for understanding how to properly invoke and interpret results from this tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 0% schema description coverage for 7 parameters, the description provides no information about any parameters. It doesn't explain what 'hostname', 'username', 'password', 'port', 'files', 'backup_dir', or 'timeout' mean in context, nor does it clarify the relationship between these parameters (e.g., that this appears to be a remote SSH backup operation). The description fails to compensate for the complete lack of schema documentation.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose3/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description '备份重要系统配置文件' (Backup important system configuration files) clearly states the action (backup) and target (system configuration files), but it's vague about scope and doesn't differentiate from sibling tools. It doesn't specify what makes files 'important' or whether this is for local or remote systems, though the input schema suggests remote SSH access via hostname/username parameters.

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 guidance is provided about when to use this tool versus alternatives. The description doesn't mention prerequisites, appropriate contexts, or exclusions. With sibling tools like 'remote_server_inspection' and 'security_vulnerability_scan' available, there's no indication of how this backup tool fits into the overall workflow or when it should be preferred over other inspection tools.

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/Heht571/ops-mcp-server'

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