Skip to main content

GitLab Integration Layer

[[TOC]]

MCP Client Implementation

File: sre-agent/mcp_clients/gitlab.py

from gitlab import Gitlab
from typing import Optional, Dict
import os
from datetime import datetime

class GitLabClient:
"""GitLab MCP client for incident tracking"""

def __init__(self):
self.gl = Gitlab(
url=os.getenv("GITLAB_URL", "https://gitlab.ravenhelm.dev"),
private_token=os.getenv("GITLAB_TOKEN")
)
self.project_id = os.getenv("GITLAB_PROJECT_ID", "aiops-incidents")
self.project = self.gl.projects.get(self.project_id)

def create_incident(self, alert: dict, initial_analysis: dict) -> int:
"""Create GitLab issue for incident tracking."""
labels = alert["labels"]
annotations = alert["annotations"]

description = f"""# Incident: {labels['alertname']}

**Status:** Investigating
**Severity:** {labels['severity']}
**Service:** `{labels.get('container', labels.get('service'))}`
**Started:** {alert['startsAt']}
**Agent:** sre-agent-v2.1.4

---

## Alert Details
- **Trigger:** {annotations.get('summary', 'N/A')}
- **Description:** {annotations.get('description', 'N/A')}
- **Grafana Dashboard:** [View Alert](./alertgeneratorurl)

---

## Agent Timeline

### {datetime.utcnow().isoformat()} - Investigation Started
Enriching context from logs and metrics...
"""

issue = self.project.issues.create({
'title': f"Incident: {labels['alertname']}",
'description': description,
'labels': [
'incident',
f"severity::{labels['severity']}",
f"service::{labels.get('container', 'unknown')}",
'aiops-managed'
],
'assignee_ids': [],
'confidential': False,
'issue_type': 'incident'
})

return issue.iid

def add_timeline_entry(self, issue_iid: int, step: dict, result: dict):
"""Append agent action as GitLab issue comment."""
issue = self.project.issues.get(issue_iid)

status_emoji = "OK" if result.get("success") else "FAIL"

comment = f"""### {step['timestamp']} - {step['action'].replace('_', ' ').title()} [{status_emoji}]

**Reasoning:** {step.get('reasoning', 'N/A')}
"""

if step.get("command"):
comment += f"""\n**Action Taken:**\n```bash\n{step['command']}\n```\n"""

if result.get("output"):
comment += f"""\n<details>\n<summary>Output</summary>\n\n```\n{result['output'][:500]}\n```\n</details>\n"""

if result.get("confidence"):
comment += f"\n**Confidence:** {result['confidence']:.0%}"

issue.notes.create({'body': comment})

def resolve_incident(self, issue_iid: int, resolution: dict):
"""Close issue with root cause analysis summary."""
issue = self.project.issues.get(issue_iid)

rca_comment = f"""---

## Incident Resolved

**Recovery Method:** Automated (Runbook `{resolution['runbook_id']}`)

### Root Cause
{resolution['root_cause']}

**Status:** Resolved - Auto-closed by AIOps Agent
"""

issue.notes.create({'body': rca_comment})
issue.state_event = 'close'
issue.labels = issue.labels + ['auto-resolved']
issue.save()

def escalate_incident(self, issue_iid: int, reason: str, oncall_user: str):
"""Escalate to human when agent cannot resolve."""
issue = self.project.issues.get(issue_iid)

escalation = f"""---

## Escalation Required

**Reason:** {reason}

**Agent Status:** Unable to resolve autonomously
**Oncall Assigned:** @{oncall_user}

### Next Steps
Manual intervention required. Review logs and metrics attached in timeline above.
"""

issue.notes.create({'body': escalation})

# Update labels
issue.labels = issue.labels + ['escalated', 'requires-human']
issue.save()

GitLab Project Setup

Manual Setup Steps

  1. Create project: aiops-incidents
  2. Enable issue templates
  3. Create labels:
    • incident
    • severity::critical, severity::warning, severity::info
    • aiops-managed
    • escalated
    • requires-human
    • auto-resolved
  4. Create milestone: Q1 2026 Incidents
  5. Generate API token with api scope

Issue Template

File: .gitlab/issue_templates/Incident.md

## Incident Details

**Service:**
**Alert:**
**Severity:**

## Timeline

(Agent will populate automatically)

## Root Cause Analysis

(Completed on resolution)

---

/label ~incident

Environment Variables

# GitLab
GITLAB_URL=https://gitlab.ravenhelm.dev
GITLAB_TOKEN=your_gitlab_token_here
GITLAB_PROJECT_ID=aiops-incidents

Next: [[AIOps-Runbook-Registry]] - DIS schema and runbook examples