Skip to main content
Glama
BenedatLLC

Kubernetes Tools MCP Server

by BenedatLLC

get_pod_summaries

Retrieve pod summaries from Kubernetes clusters to monitor container status, restarts, and resource allocation across namespaces.

Instructions

Retrieves a list of PodSummary objects for pods in a given namespace or all namespaces.

Parameters
----------
namespace : Optional[str], default=None
    The specific namespace to list pods from. If None, lists pods from all namespaces.

Returns
-------
list of PodSummary
    A list of PodSummary objects, each providing a summary of a pod's status with the following fields:

    name : str
        Name of the pod.
    namespace : str
        Namespace in which the pod is running.
    total_containers : int
        Total number of containers in the pod.
    ready_containers : int
        Number of containers currently in ready state.
    restarts : int
        Total number of restarts for all containers in the pod.
    last_restart : Optional[datetime.timedelta]
        Time since the container last restart (None if never restarted).
    age : datetime.timedelta
        Age of the pod (current time minus creation timestamp).
    ip : Optional[str]
        Pod IP address (None if not assigned).
    node : Optional[str]
        Name of the node where the pod is running (None if not scheduled).
Raises
------
K8sConfigError
    If unable to initialize the K8S API.
K8sApiError
    If the API call to list pods fails.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
namespaceNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The handler function that implements the logic for the 'get_pod_summaries' tool. It initializes the Kubernetes client if necessary, lists pods (namespaced or all), processes each pod to extract summary information, and returns a list of PodSummary objects.
    def get_pod_summaries(namespace: Optional[str] = None) -> list[PodSummary]:
        """
        Retrieves a list of PodSummary objects for pods in a given namespace or all namespaces.
    
        Parameters
        ----------
        namespace : Optional[str], default=None
            The specific namespace to list pods from. If None, lists pods from all namespaces.
    
        Returns
        -------
        list of PodSummary
            A list of PodSummary objects, each providing a summary of a pod's status with the following fields:
    
            name : str
                Name of the pod.
            namespace : str
                Namespace in which the pod is running.
            total_containers : int
                Total number of containers in the pod.
            ready_containers : int
                Number of containers currently in ready state.
            restarts : int
                Total number of restarts for all containers in the pod.
            last_restart : Optional[datetime.timedelta]
                Time since the container last restart (None if never restarted).
            age : datetime.timedelta
                Age of the pod (current time minus creation timestamp).
            ip : Optional[str]
                Pod IP address (None if not assigned).
            node : Optional[str]
                Name of the node where the pod is running (None if not scheduled).
        Raises
        ------
        K8sConfigError
            If unable to initialize the K8S API.
        K8sApiError
            If the API call to list pods fails.
        """
        global K8S
        
        # Load Kubernetes configuration and initialize client only once
        if K8S is None:
            K8S = _get_api_client()
    
        logging.info(f"get_pod_summaries(namespace={namespace})")
        pod_summaries: list[PodSummary] = []
        
        try:
            if namespace:
                # List pods in a specific namespace
                pods = K8S.list_namespaced_pod(namespace=namespace).items
            else:
                # List pods across all namespaces
                pods = K8S.list_pod_for_all_namespaces().items
        except client.ApiException as e:
            raise K8sApiError(f"Error fetching pods: {e}") from e
    
        current_time_utc = datetime.datetime.now(datetime.timezone.utc)
    
        for pod in pods:
            pod_name = pod.metadata.name
            pod_namespace = pod.metadata.namespace
            
            total_containers = len(pod.spec.containers)
            ready_containers = 0
            total_restarts = 0
            latest_restart_time: Optional[datetime.datetime] = None
    
            if pod.status and pod.status.container_statuses:
                for container_status in pod.status.container_statuses:
                    if container_status.ready:
                        ready_containers += 1
                    
                    total_restarts += container_status.restart_count
                    
                    # Check for last restart time
                    if container_status.last_state and container_status.last_state.terminated:
                        terminated_at = container_status.last_state.terminated.finished_at
                        if terminated_at:
                            if latest_restart_time is None or terminated_at > latest_restart_time:
                                latest_restart_time = terminated_at
    
            # Calculate age
            age = datetime.timedelta(0) # Default to 0 if creation_timestamp is missing
            if pod.metadata.creation_timestamp:
                age = current_time_utc - pod.metadata.creation_timestamp
    
            # Calculate last_restart timedelta if a latest_restart_time was found
            last_restart_timedelta: Optional[datetime.timedelta] = None
            if latest_restart_time:
                last_restart_timedelta = current_time_utc - latest_restart_time
    
            # Extract IP and node information
            pod_ip = pod.status.pod_ip if pod.status and pod.status.pod_ip else None
            node_name = pod.spec.node_name if pod.spec and pod.spec.node_name else None
    
            pod_summary = PodSummary(
                name=pod_name,
                namespace=pod_namespace,
                total_containers=total_containers,
                ready_containers=ready_containers,
                restarts=total_restarts,
                last_restart=last_restart_timedelta,
                age=age,
                ip=pod_ip,
                node=node_name
            )
            pod_summaries.append(pod_summary)
        
        return pod_summaries
  • Pydantic model defining the output schema for PodSummary objects returned by get_pod_summaries.
    class PodSummary(BaseModel):
        """A summary of a pod's status like returned by `kubectl get pods -o wide`"""
        name: str
        namespace: str
        total_containers: int
        ready_containers: int
        restarts: int
        last_restart: Optional[datetime.timedelta]
        age: datetime.timedelta
        ip: Optional[str] = None
        node: Optional[str] = None
  • List of tool handler functions including get_pod_summaries, imported by mcp_server.py and wrapped into MCP Tool objects.
    TOOLS = [
        get_namespaces,
        get_node_summaries,
        get_pod_summaries,
        get_pod_container_statuses,
        get_pod_events,
        get_pod_spec,
        get_logs_for_pod_and_container,
        get_deployment_summaries,
        get_service_summaries
    ]
  • MCP server registration where TOOLS from k8s_tools.py are wrapped using Tool.from_function and passed to FastMCP server instance, registering get_pod_summaries as an MCP tool.
    if not args.mock:
        from .k8s_tools import TOOLS
    else:
        from .mock_tools import TOOLS
        logging.warning(f"Using mock versions of the tools")
    wrapped_tools = [get_tool_for_function(fn) for fn in TOOLS]
    
    mcp = FastMCP(
        name="k8stools-"+args.transport,
        tools=wrapped_tools,
        streamable_http_path="/mcp",
        stateless_http=(args.transport == 'streamable-http'),
        host=args.host,
        port=args.port,
        log_level=args.log_level,
        debug=args.debug
    )
    logging.debug(f"Settings are: {mcp.settings}")
    logging.info(f"Starting with {len(wrapped_tools)} tools on transport {args.transport}")
    # this starts the uvicorn server
    mcp.run(transport=args.transport)
Behavior4/5

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

With no annotations provided, the description carries full burden and does well by disclosing behavioral traits: it specifies the return type (list of PodSummary), documents potential exceptions (K8sConfigError, K8sApiError), and describes error conditions. However, it doesn't mention rate limits, authentication needs, or side effects like caching.

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 well-structured with clear sections (Parameters, Returns, Raises), front-loaded with the core purpose, and every sentence earns its place by providing essential information without redundancy. It's appropriately sized for a tool with one parameter and detailed return documentation.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's moderate complexity, no annotations, and the presence of a detailed output schema (which the description references), the description is complete: it covers purpose, parameter semantics, return structure, and error conditions. The output schema handles return value details, so the description appropriately focuses on higher-level context.

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

Parameters4/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. It fully documents the single parameter 'namespace', explaining its optional nature, default value (None), and semantic meaning ('specific namespace to list pods from' vs 'all namespaces'). This adds significant value beyond the bare schema.

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

Purpose5/5

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

The description clearly states the verb 'Retrieves' and resource 'list of PodSummary objects for pods', specifying it works 'in a given namespace or all namespaces'. It distinguishes from siblings like get_pod_container_statuses (container-level details) and get_pod_events (event logs) by focusing on summary-level pod status.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear context by specifying it retrieves summaries for pods in a namespace or all namespaces, but does not explicitly state when to use this tool versus alternatives like get_pod_container_statuses or get_pod_events. The namespace parameter guidance implies usage but lacks explicit sibling comparison.

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/BenedatLLC/k8stools'

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