Skip to main content
Glama
Esteban-Fonseca-DEV

Guardian MCP Toolkit

README.md
# ๐Ÿ›ก๏ธ Guardian โ€” Headless Governance Platform

**Active architecture governance for Clean Architecture, DDD, SOLID, TDD, and Security โ€” in 8 languages.**

[![npm version](https://img.shields.io/npm/v/guardian-mcp-toolkit)](https://www.npmjs.com/package/guardian-mcp-toolkit)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![Tests](https://img.shields.io/badge/tests-215%20passed-brightgreen)]()
[![Agents](https://img.shields.io/badge/agents-12-purple)]()
[![Languages](https://img.shields.io/badge/languages-8-orange)]()

Guardian is not a linter. It's a **headless active governance platform** that detects **Architectural Drift** (structural erosion) and **Semantic Violations** (naming that breaks the Ubiquitous Language) in real-time โ€” providing **Auto-Remediation** and contextual education directly in your workflow.

> **The Differentiator:** Fusion of local high-speed AST analysis with cloud semantic reasoning via Amazon Bedrock to protect your domain model.

---

## Table of Contents

- [Quick Start](#-quick-start)
- [How It Works](#-how-it-works)
- [MCP Integration (IDE)](#-mcp-integration-ide)
- [CLI Reference](#-cli-reference)
- [Agents](#-12-specialized-agents)
- [Governance Policy](#-governance-policy)
- [Custom Rules DSL](#-custom-rules-dsl)
- [Auto-Remediation](#-auto-remediation)
- [Dashboard](#-live-dashboard)
- [Live Mode](#-live-mode-guardian-watch)
- [GitHub Actions](#-github-actions--cicd)
- [AWS Cloud Mode](#-aws-cloud-mode)
- [Supported Languages](#-supported-languages)
- [Architecture](#-architecture)
- [Contributing](#-contributing)

---

## ๐Ÿš€ Quick Start

```bash
# Install globally
npm install -g guardian-mcp-toolkit

# Audit any project (auto-detects structure & language)
guardian audit /path/to/your/project

# See what was detected
guardian audit . --format json

# Auto-remediate violations
guardian fix . --apply

# Watch mode โ€” real-time feedback as you code
guardian watch .
```

**First time?** Guardian auto-detects your project structure and generates a `.guardian.json` (Governance Policy) on first run. No configuration needed to start.

---

## ๐Ÿง  How It Works

```
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                    Guardian Governance Platform               โ”‚
โ”‚                                                              โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚
โ”‚  โ”‚   CLI    โ”‚โ”€โ”€โ”€โ–ถโ”‚   MCP Server   โ”‚โ”€โ”€โ”€โ–ถโ”‚ Amazon Bedrock  โ”‚ โ”‚
โ”‚  โ”‚  (TUI)   โ”‚    โ”‚  (12 Agents)   โ”‚    โ”‚ (Claude Sonnet) โ”‚ โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚
โ”‚       โ”‚                   โ”‚                                  โ”‚
โ”‚       โ–ผ                   โ–ผ                                  โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚
โ”‚  โ”‚Dashboard โ”‚โ—€โ”€โ”€โ–ถโ”‚   EventBus     โ”‚โ”€โ”€โ”€โ–ถโ”‚   LSP Server    โ”‚ โ”‚
โ”‚  โ”‚(React/SSE)โ”‚   โ”‚  (real-time)   โ”‚    โ”‚ (IDE diagnostics)โ”‚ โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
```

Guardian operates in three layers:

1. **Local AST Analysis** โ€” Sub-second detection of structural violations (layer boundaries, DDD, security patterns)
2. **Semantic Analysis** โ€” Amazon Bedrock (Claude) analyzes naming, SOLID principles, and domain alignment
3. **Real-time Distribution** โ€” EventBus pushes results to CLI, Dashboard, LSP, and SSE simultaneously

---

## ๐Ÿ”Œ MCP Integration (IDE)

Connect Guardian to any MCP-compatible IDE (Kiro, VS Code, Cursor, Claude Desktop):

```json
{
  "mcpServers": {
    "guardian": {
      "command": "guardian",
      "args": ["mcp", "serve"]
    }
  }
}
```

Once connected, your AI assistant can use 20+ Guardian tools. Examples:

- *"Check if this import violates layer boundaries"*
- *"Scan this directory for exposed secrets"*
- *"Audit this file's SOLID compliance"*
- *"Generate the dependency graph for src/"*

---

## ๐Ÿ’ป CLI Reference

### `guardian audit [path]`

Run a full governance audit with all enabled agents.

```bash
guardian audit .                      # Audit current directory
guardian audit src/ --format json     # JSON output to stdout
guardian audit . --fail-on warning    # Fail on warnings too (strict)
guardian audit . --fail-on error      # Fail only on errors (default)
```

**Exit codes:** `0` = passed, `1` = violations found, `2` = input error

### `guardian fix [path]`

Detect and auto-remediate Architectural Drift.

```bash
guardian fix .              # Show proposed fixes (dry-run)
guardian fix . --apply      # Apply fixes automatically
```

**Supported Auto-Remediations:**
| Drift Type | Remediation |
|-----------|-------------|
| Layer boundary violation | Generate interface in domain, move impl to infra |
| Missing test file | Generate test skeleton (AAA pattern) |
| Fat interface (ISP) | Suggest split into cohesive interfaces |
| process.env in domain | Extract to infrastructure ConfigService |
| Mutable public state (DDD) | Add `readonly` modifier |
| Hardcoded secrets | Replace with env variable reference |

### `guardian watch [path]`

Live Mode โ€” real-time governance as you code.

```bash
guardian watch .                # Watch current directory
guardian watch src/ --port 4200 # Custom SSE port
```

Debounces file changes (300ms), runs only relevant agents via Smart Routing, and pushes results to:
- Terminal (stderr) โ€” immediate feedback
- SSE Channel โ€” Dashboard updates
- LSP Server โ€” IDE squiggly lines

Press `Ctrl+C` for graceful shutdown.

### `guardian dashboard`

Open the web dashboard with Health Score, Radar Chart, and Heatmap.

```bash
guardian dashboard              # Opens http://localhost:4000
guardian dashboard --port 8080  # Custom port
```

### `guardian init`

Generate a `.guardian.json` Governance Policy with defaults.

```bash
guardian init     # Creates .guardian.json in current directory
```

### `guardian agent list|enable|disable`

Manage which agents are active.

```bash
guardian agent list             # Table of all agents with status
guardian agent enable ddd-guard # Enable a specific agent
guardian agent disable tdd-strict # Disable an agent
```

### `guardian hooks install`

Install Git hooks for pre-commit and pre-push validation.

```bash
guardian hooks install    # Creates .git/hooks/pre-commit & pre-push
```

- **pre-commit**: Audits staged files, blocks commit on errors
- **pre-push**: Audits all changes since last push

### `guardian mcp serve`

Start the MCP Server for IDE integration (stdio transport).

```bash
guardian mcp serve    # Listens on stdio for MCP protocol
```

---

## ๐Ÿค– 12 Specialized Agents

### Core Agents (Architecture Governance)

| Agent | Detects | Severity |
|-------|---------|----------|
| **Clean-Guard** | Layer boundary violations (domainโ†’infra imports) | Error |
| **TDD-Strict** | Missing test files, broken Red-Green-Refactor sequence | Error |
| **DDD-Guard** | Mutable public state, direct aggregate internal access, cross-context imports | Error |
| **Security-Guard** | Hardcoded secrets (AWS, GitHub, JWT, DB URLs, PEM keys), env access outside infra | Error |
| **SOLID-Copilot** | God Objects (>200 lines, >10 methods), fat interfaces (>5 methods) | Warning |
| **Concurrency-Guard** | Unhandled promises, event listeners without cleanup, mutable exports, timers without cleanup | Warning |
| **Semantic-Naming-Guard** | Banned words (Manager, Util), empty variables, false booleans, verb inconsistency | Warning |

### Language Specialists (Idiomatic Rules)

| Agent | Language | Detects |
|-------|----------|---------|
| **Go-Idiomatic-Guard** | Go | Goroutine leaks, missing context propagation, error wrapping, interface placement |
| **Py-Async-Guard** | Python | Blocking I/O in async, circular imports, missing type hints |
| **TS-Contract-Guard** | TypeScript | `any` in domain layer, deep relative imports, unhandled promises |
| **Dart-Arch-Guard** | Dart/Flutter | Flutter imports in domain, undisposed streams, UI logic leaks |
| **DotNet-Clean-Guard** | C#/.NET | EF in domain, missing CancellationToken, DbContext leaks |

---

## ๐Ÿ“ Governance Policy

The `.guardian.json` file defines your architecture contract. Guardian auto-generates one on first run, or create it manually:

```json
{
  "version": "1.0.0",
  "executionMode": "local",
  "layers": [
    { "name": "domain", "paths": ["src/domain/**"], "allowedDependencies": [] },
    { "name": "application", "paths": ["src/services/**"], "allowedDependencies": ["domain"] },
    { "name": "infrastructure", "paths": ["src/infra/**"], "allowedDependencies": ["domain", "application"] },
    { "name": "presentation", "paths": ["src/api/**"], "allowedDependencies": ["application"] }
  ],
  "testConventions": [
    { "pattern": "**/*.test.ts" },
    { "pattern": "**/*_test.go" }
  ],
  "excludePaths": ["node_modules", "dist", "vendor", ".git"],
  "ddd": {
    "aggregates": {
      "Order": {
        "root": "src/domain/order/Order.ts",
        "internals": ["src/domain/order/OrderItem.ts", "src/domain/order/OrderStatus.ts"]
      }
    },
    "boundedContexts": {
      "orders": ["src/domain/order/**", "src/services/order/**"],
      "users": ["src/domain/user/**", "src/services/user/**"]
    }
  },
  "semantic_naming": {
    "enabled": true,
    "engine": "local",
    "banned_words": ["Manager", "Util", "Helper", "Service", "Base", "Common"]
  },
  "bedrock": {
    "enabled": false,
    "model_id": "anthropic.claude-3-5-sonnet-20241022-v2:0",
    "fallback_model_id": "anthropic.claude-3-haiku-20240307-v1:0"
  }
}
```

### Layer Rules

The `layers` array defines your architecture. Each layer declares:
- `name` โ€” Layer identifier
- `paths` โ€” Glob patterns matching files in this layer
- `allowedDependencies` โ€” Which other layers this layer may import from

**Example violation:** A file in `src/domain/` imports from `src/infra/` โ†’ **Architectural Drift detected**.

---

## ๐Ÿ“ Custom Rules DSL

Define project-specific rules in the `rules` section of your Governance Policy:

```json
{
  "rules": [
    {
      "id": "no-axios-in-domain",
      "layer": "domain",
      "severity": "error",
      "message": "Domain layer cannot depend on HTTP libraries",
      "forbidden_imports": ["axios", "node-fetch", "got"]
    },
    {
      "id": "max-method-length",
      "severity": "warning",
      "message": "Methods should be concise",
      "max_lines": 30
    },
    {
      "id": "domain-must-export-interface",
      "layer": "domain",
      "severity": "warning",
      "message": "Domain files should export at least one interface",
      "required_patterns": ["export\\s+interface"]
    }
  ]
}
```

**Three rule types:**
- `forbidden_imports` โ€” Block specific imports in a layer
- `max_lines` โ€” Enforce method/function length limits
- `required_patterns` โ€” Require regex patterns in files

---

## ๐Ÿ”ง Auto-Remediation

Guardian doesn't just detect โ€” it fixes. Each remediation includes a contextual explanation of *why* the pattern is Architectural Drift.

```bash
$ guardian fix .

  Guardian Fix โ€” 3 fixes available:

  [FIX] src/domain/UserService.ts:3
        Action: Generate interface in domain layer and move implementation to infrastructure
        + export interface IUserRepository { ... }
        - import { PgUserRepo } from "../infrastructure/..."

  [FIX] src/domain/Order.ts:5
        Action: Add 'readonly' modifier to public property
        - public status: string
        + public readonly status: string

  [FIX] src/application/Handler.ts
        Action: Generate test skeleton: Handler.test.ts

  Use --apply to apply fixes automatically.
```

---

## ๐Ÿ“Š Live Dashboard

```bash
guardian dashboard
```

Opens a React SPA at `http://localhost:4000` with:

- **Health Score Gauge** โ€” Animated 0-100 indicator of overall architecture health
- **Radar Chart** โ€” Compliance percentage per agent (7 axes)
- **Heatmap** โ€” Module-level visualization of Architectural Drift density
- **Real-time updates** โ€” Connects via SSE when `guardian watch` is active

Click any module in the Heatmap to see detailed violations grouped by agent and severity.

---

## ๐Ÿ‘๏ธ Live Mode (`guardian watch`)

The killer feature for demos and daily development:

```bash
guardian watch src/
```

1. **File saved** โ†’ FileWatcher detects change (chokidar)
2. **Debounce** (300ms) โ†’ Groups rapid saves into one analysis
3. **Smart Routing** โ†’ Only relevant agents run (domain file? โ†’ Clean-Guard + DDD-Guard)
4. **AST Cache** โ†’ Unchanged files skip parsing (LRU, 500 entries)
5. **EventBus** โ†’ Results broadcast to CLI, Dashboard, and LSP simultaneously

**Output in terminal:**
```
  โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
  โ”‚ ARCHITECTURAL DRIFT DETECTED                        โ”‚
  โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ
   Agent    : [DDD-Guard]
   File     : src/domain/order/Order.ts:5
   Rule     : DDD_MUTABLE_PUBLIC_STATE

   Reasoning:
   Class 'Order' exposes mutable public property 'status'.
   This breaks aggregate encapsulation in DDD.

   Auto-Remediation:
   โฏ Run `guardian fix --target Order.ts`
```

---

## โšก GitHub Actions / CI/CD

### Using the composite action

```yaml
name: Guardian Governance Audit
on: [pull_request]

jobs:
  audit:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write
    steps:
      - uses: actions/checkout@v4
      - uses: guardian-mcp/action@v1
        with:
          path: '.'
          fail-on: 'error'
          generate-pr-comment: 'true'
```

**Action features:**
- Posts a PR comment with violation table (File, Line, Agent, Severity, Description)
- Updates existing comment on re-runs (no spam)
- Configurable severity threshold
- Works without external MCP server (headless CLI)

### Standalone (no action dependency)

```yaml
- uses: actions/setup-node@v4
  with: { node-version: '20' }
- run: npm install -g guardian-mcp-toolkit
- run: guardian audit . --fail-on error
```

---

## โ˜๏ธ AWS Cloud Mode

For large codebases, delegate analysis to AWS Lambda:

```json
{ "executionMode": "cloud" }
```

- **7 Lambda functions** (one per core agent)
- **API Gateway** REST endpoint per agent
- **CDK Stack** for one-command deployment: `cd infra && cdk deploy`
- **Fallback**: If Lambda fails, analysis runs locally

```bash
cd infra
cdk deploy   # Deploys all Lambdas + API Gateway
```

---

## ๐ŸŒ Supported Languages

| Language | Import Detection | Layer Analysis | Idiomatic Rules | Smart Routing |
|----------|:---------------:|:--------------:|:---------------:|:-------------:|
| TypeScript/JS | โœ… AST | โœ… | โœ… TS-Contract-Guard | โœ… |
| Go | โœ… Regex | โœ… | โœ… Go-Idiomatic-Guard | โœ… |
| Python | โœ… Regex | โœ… | โœ… Py-Async-Guard | โœ… |
| Dart/Flutter | โœ… Regex | โœ… | โœ… Dart-Arch-Guard | โœ… |
| C#/.NET | โœ… Regex | โœ… | โœ… DotNet-Clean-Guard | โœ… |
| Java | โœ… Regex | โœ… | โ€” | โœ… |
| Kotlin | โœ… Regex | โœ… | โ€” | โœ… |
| Rust | โœ… Regex | โœ… | โ€” | โœ… |

---

## ๐Ÿ—๏ธ Architecture

```
guardian-mcp-toolkit/
โ”œโ”€โ”€ packages/
โ”‚   โ”œโ”€โ”€ shared/            # Types, interfaces, EventBus, multi-lang parser
โ”‚   โ”œโ”€โ”€ server/            # MCP Server, Smart Router, AST Cache, Custom Rules Engine
โ”‚   โ”œโ”€โ”€ clean-guard/       # Clean Architecture agent (3 tools)
โ”‚   โ”œโ”€โ”€ tdd-strict/        # TDD agent (3 tools)
โ”‚   โ”œโ”€โ”€ ddd-guard/         # DDD agent (3 tools)
โ”‚   โ”œโ”€โ”€ security-guard/    # Security agent (2 tools)
โ”‚   โ”œโ”€โ”€ solid-copilot/     # SOLID agent + Bedrock integration (2 tools)
โ”‚   โ”œโ”€โ”€ concurrency-guard/ # Concurrency agent (1 tool)
โ”‚   โ”œโ”€โ”€ semantic-naming-guard/ # Naming agent + Level1/Level2 engines (1 tool)
โ”‚   โ”œโ”€โ”€ lang-specialists/  # 5 language-specific agents (5 tools)
โ”‚   โ”œโ”€โ”€ cli/               # Terminal UX (9 commands, FileWatcher, fixEngine)
โ”‚   โ”œโ”€โ”€ lsp/               # LSP Server (diagnostics + Code Actions)
โ”‚   โ”œโ”€โ”€ dashboard/         # Express server + React SPA (Chart.js)
โ”‚   โ””โ”€โ”€ lambda/            # AWS Lambda handlers (7 functions)
โ”œโ”€โ”€ infra/                 # CDK Stack (Lambda + API Gateway)
โ”œโ”€โ”€ action/                # GitHub Action (composite)
โ”œโ”€โ”€ scripts/               # Deploy, bundle, and demo scripts
โ”œโ”€โ”€ docs/                  # Pitch deck, metrics, demo script
โ””โ”€โ”€ .guardian.json         # Self-governance (Guardian audits itself)
```

---

## ๐Ÿงช Testing

```bash
pnpm test          # Run all tests (215+ across 39 files)
pnpm build         # Build all packages
pnpm test -- --run # Run without watch mode
```

- **Property-Based Testing** with fast-check (20+ correctness properties, 100 iterations each)
- **Unit tests** for all agents and tools
- **Integration tests** for CLI, Dashboard, and Lambda handlers

---

## ๐Ÿค Contributing

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/new-agent`)
3. Write tests first (TDD โ€” Guardian enforces this!)
4. Run `guardian audit .` โ€” ensure zero errors
5. Submit a Pull Request

---

## ๐Ÿ“„ License

MIT โ€” [Edwin Esteban Fonseca](https://github.com/Esteban-Fonseca-DEV)

Maintenance

ActivitySlowing
ResponsivenessNo issues