gitops-drift-agent

gitops-drift-agent

Enables detection and remediation of Kubernetes GitOps drift via MCP tools, supporting drift detection, policy evaluation, patch application, PR generation, and audit trail retrieval.

Category
访问服务器

README

GitOps Drift Remediation Agent

License: Apache 2.0 Node.js Version TypeScript

A production-grade autonomous agent that connects to Kubernetes clusters and GitOps repositories, identifies unauthorized state drift, generates safe remediation strategies, and executes automated API patches or Pull Requests.


Table of Contents


Overview

The GitOps Drift Remediation Agent is an autonomous, policy-driven platform that continuously monitors the live state of Kubernetes resources against their declared GitOps source of truth. When drift is detected, the agent evaluates applicable remediation policies, computes minimal JSON Patch operations, and either applies them directly via the Kubernetes API or opens Pull Requests against the GitOps repository — all with full audit trails.

Core Principles

  • Minimal blast radius: patches are computed as the smallest possible diff, never full resource replacements
  • Policy-first: every remediation action is gate-kept by configurable, versioned policies with risk tiers
  • Immutable audit log: every decision, detection and mutation is recorded with cryptographic context
  • GitOps-native: the agent is itself managed by GitOps and emits PRs back to the repository
  • MCP-ready: exposes all capabilities as MCP tools for LLM-agent integration

Architecture

┌─────────────────────────────────────────────────────────────────────┐
│                    GitOps Drift Remediation Agent                   │
│                                                                     │
│  ┌─────────────┐    ┌──────────────┐    ┌────────────────────────┐ │
│  │  AST Differ │───▶│ Policy Engine│───▶│    Patch Engine        │ │
│  │             │    │              │    │                        │ │
│  │ • Deep diff │    │ • Risk tiers │    │ • JSON Patch RFC 6902  │ │
│  │ • Field     │    │ • Allow/deny │    │ • K8s API apply        │ │
│  │   tracking  │    │ • Dry-run    │    │ • PR generation        │ │
│  │ • Severity  │    │ • Approvals  │    │ • Rollback support     │ │
│  └─────────────┘    └──────────────┘    └────────────────────────┘ │
│         │                  │                       │                │
│         └──────────────────┴───────────────────────┘                │
│                            │                                        │
│                   ┌────────▼────────┐                               │
│                   │  Audit Logger   │                               │
│                   │                 │                               │
│                   │ • Structured    │                               │
│                   │   JSON logs     │                               │
│                   │ • Event chain   │                               │
│                   │ • Pino backend  │                               │
│                   └─────────────────┘                               │
│                                                                     │
│  ┌──────────────────────────────────────────────────────────────┐  │
│  │                      MCP Server                              │  │
│  │  detect_drift │ list_policies │ remediate │ get_audit_trail  │  │
│  └──────────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────────┘
         │                                          │
         ▼                                          ▼
  ┌─────────────┐                          ┌───────────────┐
  │  Kubernetes │                          │  GitOps Repo  │
  │  Cluster(s) │                          │  (Git/GitHub) │
  └─────────────┘                          └───────────────┘

Features

Feature Description
Drift Detection Deep AST-based diffing of live vs desired Kubernetes resource state
Risk Classification Automated severity scoring (critical / high / medium / low) per field path
Policy Engine Declarative, versioned policies with allow/deny rules, dry-run, and approval gates
Patch Engine RFC 6902 JSON Patch computation with K8s server-side apply support
GitOps PRs Automated Pull Request generation with drift diff and remediation rationale
Audit Trail Immutable structured audit logs with full decision chains
MCP Server All agent capabilities exposed as MCP tools for AI agent orchestration
CLI Full-featured CLI for interactive and automated operation

Installation

Prerequisites

  • Node.js >= 20.0.0
  • kubectl configured with target cluster access
  • Git credentials for GitOps repository (for PR mode)

Install from source

git clone https://github.com/your-org/gitops-drift-remediation-agent.git
cd gitops-drift-remediation-agent
npm install
npm run build
npm link   # optional: makes `drift-agent` available globally

Configuration

All configuration is passed via environment variables or a config file.

Environment Variables

Variable Required Default Description
KUBECONFIG No ~/.kube/config Path to kubeconfig file
KUBECONTEXT No current-context Kubernetes context to use
GITOPS_REPO_URL No — GitOps repository URL for PR mode
GITOPS_BRANCH No main Target branch for PRs
GITOPS_TOKEN No — Git provider token (GitHub/GitLab)
POLICY_CONFIG_PATH No ./policies.yaml Path to remediation policy config
AUDIT_LOG_PATH No ./audit.log Audit log output path
AUDIT_LOG_LEVEL No info Log level (debug/info/warn/error)
DRY_RUN No false Global dry-run mode
MCP_PORT No 3000 MCP server HTTP port
NAMESPACE_FILTER No * Comma-separated namespace filter

Usage

CLI Commands

# Detect drift across all namespaces
drift-agent detect --namespace production --output json

# Detect and auto-remediate with policy gate
drift-agent remediate --namespace production --policy strict --dry-run

# List active policies
drift-agent policy list

# Show audit trail for a resource
drift-agent audit --resource deployments/my-app --namespace production

# Start MCP server
drift-agent mcp-server --port 3000

Programmatic API

import { AstDiffer } from './src/detector/ast-differ';
import { RemediationPolicy } from './src/policy/remediation-policy';
import { PatchEngine } from './src/remediator/patch-engine';

const differ = new AstDiffer();
const drifts = await differ.detectDrift(liveResource, desiredResource);

const policy = new RemediationPolicy(policyConfig);
const decision = await policy.evaluate(drifts, resourceContext);

if (decision.approved) {
  const engine = new PatchEngine(k8sClient);
  await engine.applyRemediation(decision.patches, resourceRef);
}

MCP Server

The agent exposes an MCP (Model Context Protocol) server that makes all agent capabilities available as tools for LLM-based agents (Claude, GPT-4, etc.).

Starting the Server

drift-agent mcp-server --port 3000
# or
npm run mcp:server

Available MCP Tools

Tool Description
detect_drift Detect drift for a resource or namespace
list_policies List all configured remediation policies
evaluate_policy Evaluate drift against a specific policy
apply_remediation Apply computed remediation patches
get_audit_trail Retrieve audit events for a resource
generate_pr Generate a GitOps PR for drift remediation
rollback_remediation Roll back a previously applied remediation

MCP Client Configuration

{
  "mcpServers": {
    "gitops-drift-agent": {
      "url": "http://localhost:3000/mcp",
      "transport": "http"
    }
  }
}

Policy Engine

Policies are defined declaratively and control every aspect of the remediation lifecycle.

Policy Structure

apiVersion: drift.gitops.io/v1
kind: RemediationPolicy
metadata:
  name: production-strict
spec:
  riskTier: high
  autoRemediate: false
  requireApproval: true
  dryRunFirst: true
  rules:
    - field: "spec.replicas"
      action: restore
      severity: high
    - field: "spec.template.spec.containers[*].image"
      action: block
      severity: critical
  excludeFields:
    - "metadata.annotations['kubectl.kubernetes.io/last-applied-configuration']"
    - "metadata.resourceVersion"
    - "metadata.uid"

Audit & Telemetry

Every agent action is recorded in structured JSON format:

{
  "timestamp": "2024-06-01T12:00:00.000Z",
  "eventId": "evt_01J0ABC123",
  "eventType": "DRIFT_DETECTED",
  "severity": "high",
  "resource": {
    "kind": "Deployment",
    "name": "my-app",
    "namespace": "production",
    "apiVersion": "apps/v1"
  },
  "drift": {
    "field": "spec.replicas",
    "desired": 3,
    "live": 1,
    "changeType": "edited"
  },
  "policy": {
    "name": "production-strict",
    "decision": "remediate",
    "riskTier": "high"
  },
  "actor": {
    "agentVersion": "1.0.0",
    "kubeContext": "prod-cluster"
  }
}

Development

# Install dependencies
npm install

# Run in development mode (ts-node)
npm run dev -- detect --namespace default

# Type check only
npm run typecheck

# Lint
npm run lint

# Format
npm run format

# Build
npm run build

Testing

# Run all tests
npm test

# Run with coverage
npm run test:coverage

# Run in watch mode
npm run test:watch

Tests are organized under tests/ and use Jest with ts-jest. Mocks are provided for the Kubernetes client and file system operations.


Security Considerations

  1. Least privilege: The agent requires only get, list, watch, and patch permissions on target resources — never delete or create
  2. Dry-run by default: All policy tiers default to dry-run until explicitly enabled
  3. Approval gates: High and critical risk changes require explicit approval via policy
  4. Audit immutability: Audit logs are append-only; log rotation is handled externally
  5. Secret masking: Secret resource values are always redacted in logs and PRs
  6. Kubeconfig isolation: The agent never mutates the kubeconfig

Contributing

See CONTRIBUTING.md. All contributions require:

  • Passing test suite with >= 80% coverage
  • No new lint warnings
  • Audit log entries for any new mutation paths
  • Policy evaluation for any new remediation actions

License

Apache 2.0 — see LICENSE.

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选