feat(mcp): diagnostic tools — overview, hosts, monitors, alerts, metrics, audit
MCP-4 of milestone 461 "MCP server: Steward as an LLM-inspectable, LLM-operable hub". Twelve read-only viewer tools: - get_overview: what is wrong now, ranked critical-then-oldest. Failing monitors with their error and when the run of failures began, firing, pending and still-breaching acknowledged alerts, TLS certificates expiring within 14 days, agents that stopped reporting, hosts over the configured CPU/memory/disk thresholds (Settings > Thresholds), failed Ansible runs in the last 24h, and findings from enabled plugins through a new optional `mcp_overview(db)` plugin hook. Each finding names the call that shows its evidence. - list_hosts, get_host, get_host_metrics - list_monitors, get_monitor (HTTP header values and URL passwords are redacted) - list_alerts, get_alert_history, list_alert_rules, list_maintenance_windows - query_metrics: the whole metric store, narrowed one argument at a time (sources > resources > latest values > a series summary) - list_audit_events Shared shaping in steward/mcp/tools/_shape.py: UTC ISO times with age_s, bounded lists that say when and how they were cut, series as min/avg/max/p95/last plus a ≤60-point series, lookup by id or case-insensitive name with a did-you-mean, and a range argument that refuses an unknown key instead of reading it as 24h. New core reads in steward/core/metric_series.py (sources and resources via loose index scans, latest values via DISTINCT ON, series across the raw/hourly-rollup seam). monitors/service.py gains monitor_states, down_since and recent_failures; agent_overview_by_host now carries the fullest disk and the last sample time. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
"""The audit log: who changed what in Steward, including changes made through MCP."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from steward.models.audit import AuditEvent
|
||||
from steward.models.users import UserRole
|
||||
|
||||
from ._shape import age_s, bounded, clamp_limit, db_session, iso, lookback
|
||||
|
||||
|
||||
async def list_audit_events(action: str = "", user: str = "", entity_type: str = "",
|
||||
range: str = "7d", limit: int = 50) -> dict:
|
||||
"""Changes recorded in Steward's audit log, newest first.
|
||||
|
||||
action: a prefix of the action name, e.g. "monitor." or "ansible.run";
|
||||
empty for all.
|
||||
user: a username, exactly; "system" for automated changes.
|
||||
entity_type: e.g. "monitor", "host", "alert_rule"; empty for all.
|
||||
range: "1h", "6h", "24h", "7d" (default) or "30d".
|
||||
limit: default 50, max 500.
|
||||
|
||||
Answers "what changed before this broke?": line an event's `at` up against
|
||||
a monitor's down_since or an alert's since.
|
||||
"""
|
||||
since, key = lookback(range)
|
||||
limit = clamp_limit(limit, 50, 500)
|
||||
stmt = (select(AuditEvent).where(AuditEvent.timestamp >= since)
|
||||
.order_by(AuditEvent.timestamp.desc()).limit(limit + 1))
|
||||
if action:
|
||||
esc = action.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||
stmt = stmt.where(AuditEvent.action.like(esc + "%", escape="\\"))
|
||||
if user:
|
||||
stmt = stmt.where(AuditEvent.username == user)
|
||||
if entity_type:
|
||||
stmt = stmt.where(AuditEvent.entity_type == entity_type)
|
||||
async with db_session() as db:
|
||||
rows = list((await db.execute(stmt)).scalars())
|
||||
|
||||
def _detail(raw):
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
return json.loads(raw)
|
||||
except ValueError:
|
||||
return raw[:500]
|
||||
|
||||
events = [
|
||||
{
|
||||
"at": iso(e.timestamp),
|
||||
"age_s": age_s(e.timestamp),
|
||||
"user": e.username,
|
||||
"action": e.action,
|
||||
"entity_type": e.entity_type,
|
||||
"entity_id": e.entity_id,
|
||||
"detail": _detail(e.detail_json),
|
||||
}
|
||||
for e in rows
|
||||
]
|
||||
out = {"range": key, **bounded(events, limit, key="events")}
|
||||
if out["truncated"]:
|
||||
out["total"] = None
|
||||
out["more"] = (f"More than {limit} events in range. Pass a larger `limit` (max 500), "
|
||||
"a shorter `range`, or filter by `action`, `user` or `entity_type`.")
|
||||
return out
|
||||
|
||||
|
||||
def register(register_tool) -> None:
|
||||
register_tool(list_audit_events, role=UserRole.viewer, read_only=True)
|
||||
Reference in New Issue
Block a user