Skip to main content
Glama

GitOps Drift Remediation Agent

License: Apache 2.0 Node.js Version TypeScript

一个生产级自主代理,连接 Kubernetes 集群和 GitOps 仓库,识别未经授权的状态漂移,生成安全的修复策略,并执行自动化的 API 补丁或拉取请求。


目录


Related MCP server: GitHub Flow MCP

概述

GitOps Drift Remediation Agent 是一个自主的、策略驱动的平台,持续将 Kubernetes 资源的实时状态与其声明的 GitOps 真实来源进行对比。当检测到漂移时,代理会评估适用的修复策略,计算最小的 JSON Patch 操作,并通过 Kubernetes API 直接应用它们,或针对 GitOps 仓库打开拉取请求——所有操作均带有完整的审计追踪。

核心原则

  • 最小爆炸半径:补丁计算为尽可能小的差异,绝不进行完整的资源替换

  • 策略优先:每个修复操作都由可配置的、带风险等级的版本化策略把关

  • 不可变审计日志:每个决策、检测和变更都带有加密上下文记录

  • GitOps 原生:代理本身由 GitOps 管理,并将 PR 发回仓库

  • MCP 就绪:将所有能力作为 MCP 工具暴露,用于 LLM 代理集成


架构

┌─────────────────────────────────────────────────────────────────────┐
│                    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) │
  └─────────────┘                          └───────────────┘

功能特性

功能

描述

漂移检测

基于 AST 的深度差异比较,对比实时与期望的 Kubernetes 资源状态

风险分类

按字段路径自动进行严重性评分(严重 / 高 / 中 / 低)

策略引擎

声明式、版本化的策略,包含允许/拒绝规则、试运行和审批门控

补丁引擎

RFC 6902 JSON Patch 计算,支持 K8s 服务端应用

GitOps 拉取请求

自动生成包含漂移差异和修复理由的拉取请求

审计追踪

不可变的结构化审计日志,包含完整的决策链

MCP 服务器

所有代理能力作为 MCP 工具暴露,用于 AI 代理编排

CLI

功能齐全的 CLI,支持交互式和自动化操作


安装

前提条件

  • Node.js >= 20.0.0

  • kubectl 已配置目标集群访问权限

  • 用于 GitOps 仓库的 Git 凭据(用于 PR 模式)

从源码安装

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

配置

所有配置均通过环境变量或配置文件传递。

环境变量

变量

必填

默认值

描述

KUBECONFIG

否

~/.kube/config

kubeconfig 文件路径

KUBECONTEXT

否

current-context

要使用的 Kubernetes 上下文

GITOPS_REPO_URL

否

—

PR 模式的 GitOps 仓库 URL

GITOPS_BRANCH

否

main

PR 的目标分支

GITOPS_TOKEN

否

—

Git 提供商令牌(GitHub/GitLab)

POLICY_CONFIG_PATH

否

./policies.yaml

修复策略配置路径

AUDIT_LOG_PATH

否

./audit.log

审计日志输出路径

AUDIT_LOG_LEVEL

否

info

日志级别(debug/info/warn/error)

DRY_RUN

否

false

全局试运行模式

MCP_PORT

否

3000

MCP 服务器 HTTP 端口

NAMESPACE_FILTER

否

*

逗号分隔的命名空间过滤器


使用方法

CLI 命令

# 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

程序化 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 服务器

该代理暴露了一个 MCP(Model Context Protocol)服务器,将所有代理能力作为工具提供给基于 LLM 的代理(Claude、GPT-4 等)。

启动服务器

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

可用的 MCP 工具

工具

描述

detect_drift

检测资源或命名空间的漂移

list_policies

列出所有已配置的修复策略

evaluate_policy

针对特定策略评估漂移

apply_remediation

应用计算出的修复补丁

get_audit_trail

检索资源的审计事件

generate_pr

为漂移修复生成 GitOps PR

rollback_remediation

回滚先前应用的修复

MCP 客户端配置

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

策略引擎

策略以声明方式定义,控制修复生命周期的每个方面。

策略结构

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"

审计与遥测

每个代理操作都以结构化 JSON 格式记录:

{
  "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"
  }
}

开发

# 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

测试

# Run all tests
npm test

# Run with coverage
npm run test:coverage

# Run in watch mode
npm run test:watch

测试组织在 tests/ 目录下,使用 Jest 和 ts-jest。为 Kubernetes 客户端和文件系统操作提供了模拟。


安全注意事项

  1. 最小权限:代理仅需要目标资源上的 get、list、watch 和 patch 权限——绝不需要 delete 或 create

  2. 默认试运行:所有策略层级默认试运行,直到显式启用

  3. 审批门控:高风险和严重风险变更需要通过策略显式审批

  4. 审计不可变性:审计日志仅追加;日志轮转由外部处理

  5. 机密遮蔽:Secret 资源值在日志和 PR 中始终被脱敏

  6. kubeconfig 隔离:代理从不修改 kubeconfig


贡献

参见 CONTRIBUTING.md。所有贡献需要:

  • 通过测试套件,覆盖率 >= 80%

  • 无新的 lint 警告

  • 任何新的变更路径都有审计日志条目

  • 任何新的修复操作都经过策略评估


许可证

Apache 2.0 — 参见 LICENSE。

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    C
    maintenance
    Provides MCP multi-cluster Kubernetes management and operations. It can be integrated as an SDK into your own project and includes nearly 50 built-in tools covering common DevOps and development scenarios. Supports both standard and CRD resources.
    151
    MIT
  • A
    license
    C
    quality
    D
    maintenance
    A policy-aware MCP server for GitHub and GitHub Actions that enables safe AI-assisted infrastructure workflows—inspecting repositories, preparing branches and pull requests, and constrained remote mutations behind explicit preview-bound approval tokens.
    18
    MIT
  • A
    license
    Not graded
    quality
    B
    maintenance
    Turns any AI coding agent or MCP client into a governed DevOps engineer by exposing policy-enforced tools for Kubernetes, Docker, Jira, Git/PR, CI/CD, AWS, Terraform, and incident response, with approvals, audit logging, secret redaction, and rollback enforced outside the model.
    36 PyPI
    6
    Apache 2.0