Skip to main content
Glama
Heht571
by Heht571

get_container_logs

Retrieve container logs from remote servers via SSH to monitor application behavior and troubleshoot issues by specifying parameters like container name, log tail length, and time range.

Instructions

获取指定容器的日志

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
hostnameYes
usernameYes
passwordNo
portNo
containerNo
tailNo
sinceNo
timeoutNo

Implementation Reference

  • Core handler implementation for get_container_logs: connects via SSH, executes 'docker logs' command on remote server, parses and returns logs with metadata.
    @handle_exceptions
    def get_container_logs(
        hostname: str,
        username: str,
        password: str = "",
        port: int = 22,
        container: str = "",  # 容器ID或名称
        tail: int = 100,  # 获取最后多少行日志
        since: str = "",  # 从什么时间开始的日志,例如 "2023-01-01T00:00:00"
        timeout: int = 30
    ) -> dict:
        """获取指定容器的日志"""
        result = InspectionResult()
        
        if not container:
            result.status = "error"
            result.error = "必须指定容器ID或名称"
            return result.dict()
        
        try:
            with SSHManager(hostname, username, password, port, timeout) as ssh:
                # 检查Docker是否安装
                stdin, stdout, stderr = ssh.exec_command("command -v docker")
                if not stdout.read().strip():
                    result.status = "error"
                    result.error = "Docker未安装在目标服务器上"
                    return result.dict()
                
                # 构建命令
                cmd = f"docker logs --tail {tail}"
                if since:
                    cmd += f" --since '{since}'"
                cmd += f" {container}"
                
                # 执行命令
                stdin, stdout, stderr = ssh.exec_command(cmd)
                log_output = stdout.read().decode('utf-8')
                error_output = stderr.read().decode('utf-8')
                
                if error_output:
                    result.status = "error"
                    result.error = f"获取容器日志失败: {error_output}"
                    return result.dict()
                
                # 设置结果
                result.status = "success"
                result.data = {"logs": log_output.strip().split("\n")}
                result.raw_outputs = {"container_logs": log_output}
                
                log_lines = len(log_output.strip().split("\n")) if log_output.strip() else 0
                result.summary = f"获取到容器 {container} 的 {log_lines} 行日志"
                
        except Exception as e:
            result.status = "error"
            result.error = f"获取容器日志失败: {str(e)}"
        
        return result.dict()
  • Alternative handler implementation for get_container_logs in SSE variant: similar SSH-based Docker logs retrieval.
    @handle_exceptions
    def get_container_logs(
        hostname: str,
        username: str,
        password: str = "",
        port: int = 22,
        container: str = "",  # 容器ID或名称
        tail: int = 100,  # 获取最后多少行日志
        since: str = "",  # 从什么时间开始,如 "2021-01-01T00:00:00"
        timeout: int = 30
    ) -> dict:
        """获取Docker容器的日志"""
        result = InspectionResult()
    
        if not container:
            result.status = "error"
            result.error = "必须指定容器ID或名称"
            return result.dict()
    
        try:
            with SSHManager(hostname, username, password, port, timeout) as ssh:
                # 检查Docker是否安装
                stdin, stdout, stderr = ssh.exec_command("command -v docker", timeout=timeout)
                if not stdout.read().strip():
                    result.status = "error"
                    result.error = "Docker未安装在目标服务器上"
                    return result.dict()
    
                # 构建命令
                cmd = f"docker logs --tail {tail}"
                if since:
                    cmd += f" --since '{since}'"
                cmd += f" {container}"
    
                # 执行命令
                stdin, stdout, stderr = ssh.exec_command(cmd, timeout=timeout)
                log_output = stdout.read().decode('utf-8')
                error_output = stderr.read().decode('utf-8')
    
                if error_output:
                    result.status = "error"
                    result.error = f"获取容器日志失败: {error_output}"
                    return result.dict()
    
                # 设置结果
                result.status = "success"
                result.data = {"logs": log_output.strip().split("\n")}
                result.raw_outputs = {"container_logs": log_output}
    
                log_lines = len(log_output.strip().split("\n")) if log_output.strip() else 0
                result.summary = f"获取到容器 {container} 的 {log_lines} 行日志"
    
        except Exception as e:
            result.status = "error"
            result.error = f"获取容器日志失败: {str(e)}"
    
        return result.dict()
  • Tool schema definition including name, description, and parameter types/defaults for get_container_logs.
    {"name": "get_container_logs", "description": "获取Docker容器的日志", "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": "container", "type": "str", "default": ""},
        {"name": "tail", "type": "int", "default": 100},
        {"name": "since", "type": "str", "default": ""},
        {"name": "timeout", "type": "int", "default": 30}
    ]},
  • Registration of get_container_logs in the tools dictionary and dynamic MCP tool registration.
    tools_dict = {
        'get_memory_info': get_memory_info,
        'remote_server_inspection': remote_server_inspection,
        'get_system_load': get_system_load,
        'monitor_processes': monitor_processes,
        'check_service_status': check_service_status,
        'get_os_details': get_os_details,
        'check_ssh_risk_logins': check_ssh_risk_logins,
        'check_firewall_config': check_firewall_config,
        'security_vulnerability_scan': security_vulnerability_scan,
        'backup_critical_files': backup_critical_files,
        'inspect_network': inspect_network,
        'analyze_logs': analyze_logs,
        'list_docker_containers': list_docker_containers,
        'list_docker_images': list_docker_images,
        'list_docker_volumes': list_docker_volumes,
        'get_container_logs': get_container_logs,
        'monitor_container_stats': monitor_container_stats,
        'check_docker_health': check_docker_health
    }
  • Dispatcher registration and argument handling for get_container_logs in SSE server tool handler.
    elif name == "get_container_logs":
        required_args = ["hostname", "username", "container"]
        for arg in required_args:
            if arg not in arguments:
                raise ValueError(f"Missing required argument '{arg}'")
    
        result = get_container_logs(
            hostname=arguments["hostname"],
            username=arguments["username"],
            password=arguments.get("password", ""),
            port=arguments.get("port", 22),
            container=arguments["container"],
            tail=arguments.get("tail", 100),
            since=arguments.get("since", ""),
            timeout=arguments.get("timeout", 30)
        )
Behavior1/5

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

With no annotations provided, the description carries full burden but fails to disclose behavioral traits. It doesn't mention that this likely requires SSH authentication (hostname, username, password), involves remote execution, has a timeout, or what the output format looks like. This leaves critical operational context unspecified.

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 a single, efficient sentence in Chinese, which is appropriately concise. However, it's too brief given the tool's complexity—it doesn't front-load critical information about authentication or output.

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 the tool's complexity (8 parameters, no annotations, no output schema), the description is incomplete. It lacks details on authentication, remote execution, output format, and error handling, making it inadequate for safe and effective use by an AI agent.

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?

Schema description coverage is 0%, so the description must compensate but adds no parameter information. It doesn't explain what 'container', 'tail', 'since', or other parameters mean, their formats (e.g., 'since' as timestamp), or how they affect the log retrieval. This leaves 8 parameters largely undocumented.

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 '获取指定容器的日志' (Get logs for a specified container) clearly states the verb (get) and resource (container logs), but it's vague about scope and format. It doesn't distinguish from sibling tools like 'analyze_logs' or 'monitor_container_stats' which might also involve container logs.

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 on when to use this tool versus alternatives. The description doesn't mention prerequisites, context (e.g., troubleshooting vs. monitoring), or how it differs from sibling tools like 'analyze_logs' or 'monitor_container_stats'.

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