# How to Use Alert History Tools for Monitoring Ambari Clusters

> Monitor Ambari clusters with alert history tools. Learn to query real-time and historical alert data using the get_alerts_history tool for efficient cluster management.

- Repository: [JungJungIn/mcp-ambari-api](https://github.com/call518/mcp-ambari-api)
- Tags: how-to-guide
- Published: 2026-02-26

---

**The `get_alerts_history` tool in the mcp-ambari-api repository provides a unified interface for querying both real-time and historical alert data from Apache Ambari clusters through the Model Context Protocol (MCP).**

Alert history tools for monitoring are essential for maintaining cluster health and investigating past incidents. The `call518/mcp-ambari-api` project exposes these capabilities as MCP tools, allowing you to retrieve current alerts or deep-dive into historical records without writing custom REST clients. This guide explains how to leverage the `get_alerts_history` tool to monitor your Ambari-managed clusters effectively.

## Understanding the Alert History Architecture

The alert history functionality is implemented across two primary files in the repository, working together to handle API communication, data transformation, and output formatting.

### Core Components and File Locations

The implementation spans the following key files:

- **[`src/mcp_ambari_api/mcp_main.py`](https://github.com/call518/mcp-ambari-api/blob/main/src/mcp_ambari_api/mcp_main.py)** (line 2028): Contains the `get_alerts_history` tool definition, argument parsing, endpoint selection, and fallback logic for timestamp filtering.
- **[`src/mcp_ambari_api/functions.py`](https://github.com/call518/mcp-ambari-api/blob/main/src/mcp_ambari_api/functions.py)** (line 1456): Houses `format_alerts_output`, which dispatches to specific formatters including `format_alerts_compact` (line 1559), `format_alerts_summary`, and `format_alerts_detailed`.
- **[`src/mcp_ambari_api/functions.py`](https://github.com/call518/mcp-ambari-api/blob/main/src/mcp_ambari_api/functions.py)** (line 1150): Provides utility functions including `format_timestamp`, `safe_timestamp_compare`, and `get_current_time_context` for handling date conversions and time-based filtering.

### Two Operational Modes: Current vs. History

The tool operates in two distinct modes, selected via the `mode` parameter:

| Mode | Ambari Endpoint | Use Case |
|------|----------------|----------|
| `current` | `/clusters/<cluster>/alerts` | Real-time health checks and active alert monitoring |
| `history` | `/clusters/<cluster>/alert_history` | Trend analysis, incident investigation, and historical reporting |

When using `mode="history"`, the tool automatically applies sorting by state and timestamp in descending order, and supports pagination through the `page_size` and `start_page` parameters.

## Querying Alert History with get_alerts_history

The `get_alerts_history` tool accepts comprehensive filtering parameters to narrow down results to specific services, hosts, time ranges, and severity states.

### Basic Parameters and Filtering

The tool supports the following key parameters for refining your queries:

- **`cluster_name`**: The target Ambari cluster (required).
- **`service_name`**: Filter to a specific service (e.g., "HDFS", "YARN").
- **`host_name`**: Filter to alerts from a specific host.
- **`state_filter`**: Filter by alert state ("CRITICAL", "WARNING", "OK", "UNKNOWN").
- **`definition_name`**: Filter by specific alert definition.
- **`maintenance_state`**: Filter by maintenance state.

### Handling Timestamps and Pagination

For historical queries, timestamp parameters accept either integer milliseconds since epoch or numeric strings:

- **`from_timestamp`**: Start of the time range (inclusive).
- **`to_timestamp`**: End of the time range (inclusive).
- **`page_size`**: Number of records per request (default varies).
- **`start_page`**: Page offset for pagination (0-based).

If Ambari rejects timestamp predicates due to type mismatches, the implementation automatically falls back to fetching without time predicates and applies client-side filtering using `safe_timestamp_compare`.

```python
import asyncio
from mcp_ambari_api.mcp_main import get_alerts_history

async def fetch_critical_history():
    """Retrieve critical HDFS alerts from the past 24 hours."""
    import time
    
    now_ms = int(time.time() * 1000)
    day_ago_ms = now_ms - (24 * 60 * 60 * 1000)
    
    result = await get_alerts_history(
        mode="history",
        cluster_name="production_cluster",
        service_name="HDFS",
        state_filter="CRITICAL",
        from_timestamp=day_ago_ms,
        to_timestamp=now_ms,
        format="compact",
        limit=50,
        include_time_context=True
    )
    return result

# Run the async function

history = asyncio.run(fetch_critical_history())
print(history)

```

## Formatting and Output Options

The tool provides three distinct output formats to suit different monitoring workflows, controlled by the `format` parameter.

### Compact, Summary, and Detailed Views

The `format_alerts_output` dispatcher in [`functions.py`](https://github.com/call518/mcp-ambari-api/blob/main/functions.py) routes to specific formatters based on the `format` parameter:

- **`compact`** (default): Produces a column-based table with one line per alert, showing timestamp, state, service, host, and definition name. Implemented in `format_alerts_compact` at line 1559.
- **`summary`**: Aggregates alerts by state and service, providing high-level counts suitable for dashboards. Implemented in `format_alerts_summary`.
- **`detailed`**: Returns full alert objects with all available fields, including alert text, component names, and metadata. Implemented in `format_alerts_detailed`.

```python

# Example: Comparing output formats

async def compare_formats():
    base_params = {
        "mode": "current",
        "cluster_name": "dev_cluster",
        "service_name": "YARN",
        "limit": 5
    }
    
    # Compact view for quick scanning

    compact = await get_alerts_history(**base_params, format="compact")
    
    # Detailed view for investigation

    detailed = await get_alerts_history(**base_params, format="detailed")
    
    return compact, detailed

compact_view, detailed_view = asyncio.run(compare_formats())
print("=== COMPACT ===")
print(compact_view)
print("\n=== DETAILED ===")
print(detailed_view)

```

## Practical Examples for Monitoring Workflows

These real-world patterns demonstrate how to integrate alert history tools for monitoring into your operational procedures.

### Retrieving Critical Alerts from the Last 24 Hours

This pattern is essential for daily health checks and incident response:

```python
import asyncio
import time
from mcp_ambari_api.mcp_main import get_alerts_history

async def daily_critical_check(cluster_name: str):
    """Fetch all critical alerts from the last 24 hours across all services."""
    now_ms = int(time.time() * 1000)
    day_ago_ms = now_ms - (24 * 60 * 60 * 1000)
    
    result = await get_alerts_history(
        mode="history",
        cluster_name=cluster_name,
        state_filter="CRITICAL",
        from_timestamp=day_ago_ms,
        to_timestamp=now_ms,
        format="compact",
        limit=100,
        include_time_context=True
    )
    return result

# Execute for production cluster

alerts = asyncio.run(daily_critical_check("production_hdp"))
print(alerts)

```

### Paginating Through Large Historical Datasets

When investigating incidents that occurred weeks ago or analyzing long-term trends, you'll encounter large result sets. Use pagination to retrieve data in manageable chunks:

```python
async def fetch_monthly_trend(cluster_name: str, service: str):
    """Retrieve all alerts for a service over a month using pagination."""
    # January 2024 example timestamps (milliseconds)

    start_ts = 1704067200000  # Jan 1, 2024

    end_ts = 1706745600000    # Feb 1, 2024

    
    all_alerts = []
    page_size = 200
    start_page = 0
    
    while True:
        batch = await get_alerts_history(
            mode="history",
            cluster_name=cluster_name,
            service_name=service,
            from_timestamp=start_ts,
            to_timestamp=end_ts,
            page_size=page_size,
            start_page=start_page,
            format="summary"  # Use summary for aggregation

        )
        
        if not batch or "No alerts" in batch:
            break
            
        all_alerts.append(batch)
        start_page += 1
        
        # Safety limit to prevent infinite loops

        if start_page > 50:
            break
    
    return all_alerts

# Fetch YARN history for analysis

yarn_history = asyncio.run(fetch_monthly_trend("analytics_cluster", "YARN"))

```

## Summary

The alert history tools for monitoring in the mcp-ambari-api repository provide a robust interface for querying Ambari cluster health data through the Model Context Protocol. Key takeaways include:

- **Dual-mode operation**: Use `mode="current"` for real-time alerts via `/clusters/<cluster>/alerts` or `mode="history"` for historical analysis via `/clusters/<cluster>/alert_history`.
- **Flexible filtering**: Narrow results by service, host, state (CRITICAL, WARNING), and precise time ranges using millisecond timestamps.
- **Robust fallback**: The implementation automatically handles Ambari timestamp predicate failures by falling back to client-side filtering via `safe_timestamp_compare`.
- **Multiple output formats**: Choose `compact` for quick scanning, `summary` for dashboards, or `detailed` for incident investigation.
- **Pagination support**: Handle large historical datasets efficiently using `page_size` and `start_page` parameters.

## Frequently Asked Questions

### How do I convert human-readable dates to the timestamps required by get_alerts_history?

The tool expects timestamps in **milliseconds since epoch** (Unix timestamp × 1000). In Python, convert datetime objects using `int(datetime.timestamp() * 1000)` or use `time.time() * 1000` for the current time. The implementation in [`mcp_main.py`](https://github.com/call518/mcp-ambari-api/blob/main/mcp_main.py) automatically coerces string inputs to integers using `_coerce_ts`, but providing integers directly is recommended for precision.

### What is the difference between the compact, summary, and detailed output formats?

The **compact** format (default) displays one alert per line in a columnar layout showing timestamp, state, service, host, and definition name—ideal for quick terminal scanning. The **summary** format aggregates alerts by state and service, providing high-level counts suitable for dashboard widgets or executive summaries. The **detailed** format returns complete alert objects with all metadata fields, including full alert text and component details, making it optimal for incident root-cause analysis.

### How does the tool handle large historical datasets that span thousands of alerts?

For large result sets, the tool implements **pagination** through the `page_size` and `start_page` parameters. When `mode="history"` is specified, the implementation automatically adds `from` and `page_size` parameters to the Ambari REST query. If Ambari returns more data than expected or if you need to traverse large windows, increment `start_page` (0-based) to retrieve subsequent batches. The tool also includes a fallback mechanism that filters timestamps client-side if the Ambari server rejects timestamp predicates, ensuring robust data retrieval even with complex queries.

### Can I filter alerts by specific services or hosts when querying history?

Yes, the `get_alerts_history` tool supports granular filtering through the `service_name` and `host_name` parameters. When provided, these parameters scope the query to specific Ambari services (e.g., "HDFS", "YARN") or individual hosts. Additionally, you can filter by `state_filter` (CRITICAL, WARNING, OK, UNKNOWN) and `definition_name` to target specific alert types. These filters work in both `current` and `history` modes, though they are particularly valuable in history mode for investigating past issues affecting specific cluster components.