npm package: @skyastrall/mcp-guardian
Description: MCP Guardian - AI coding assistant memory and discipline layer
Author: SkyAstrall
Latest version: 0.1.7

# Guardian MCP v0.1.7

[![npm version](https://img.shields.io/npm/v/@skyastrall/mcp-guardian)](https://www.npmjs.com/package/@skyastrall/mcp-guardian)

[![npm downloads](https://img.shields.io/npm/dm/@skyastrall/mcp-guardian)](https://www.npmjs.com/package/@skyastrall/mcp-guardian)

**Stop AI from hallucinating code. Give it memory and discipline.**

AI coding tools like Claude Code, Cursor, and Windsurf have a problem: they hallucinate functions that already exist, break working code with unpredictable edits, and forget everything between sessions.

Guardian fixes this by giving AI persistent memory, real-time code tracking across 17 languages, and enforcing a disciplined workflow.

> **⚠️ IMPORTANT**: Guardian tools are invoked automatically in **Claude Code (latest version)**, but may still require explicit prompting in some cases. For other AI tools (Cursor, Windsurf), you must **explicitly tell your AI** to use it:
>
> ```
> "Use Guardian to implement this feature"
> "Use Guardian gates to build authentication"
> "Check with Guardian if this function exists"
> ```
>
> Without this prompt, AI won't invoke Guardian's MCP tools.

---

## Quick Start

### 1. Get Your API Key

Visit **[guardianmcp.dev](https://guardianmcp.dev/)** and get your free API key.

### 2. Install Guardian

Add to your MCP client config (e.g., `~/.config/claude/claude_desktop_config.json` or `%APPDATA%\Claude\claude_desktop_config.json` on Windows):

```json
{
  "mcpServers": {
    "guardian": {
      "command": "npx",
      "args": ["-y", "@skyastrall/mcp-guardian@latest"],
      "env": {
        "GUARDIAN_API_KEY": "gd_your_api_key_here"
      }
    }
  }
}
```

**Replace `gd_your_api_key_here` with your actual API key from guardianmcp.dev.**

### 3. Restart Your AI Tool

Restart Claude Code, Cursor, or your MCP-compatible tool.

### 4. Configure AI Integration (Optional but Recommended)

To make your AI tool **automatically** use Guardian without prompting, add a rules file to your project:

#### For Claude Code (`CLAUDE.md`)
Create `CLAUDE.md` in your project root:

```markdown
# Guardian Protocol (Automated Engineering)
This project uses the Guardian MCP to ensure code quality and architectural integrity.

## Trigger-Response Rules (Strict)
1. **IF** I ask for a plan, architecture, or complex feature → **THEN** Call `start_engineering` immediately. Do NOT write a text plan.
2. **IF** I ask to edit code → **THEN** Call `get_decision` first to check for constraints.
3. **IF** I ask to modify an API → **THEN** Call `get_api_contract` first.

## Workflow
- **New Features**: `start_engineering` → `submit_analysis` → `submit_plan` → `approve_plan` → `get_next_step`
- **Verification**: Use `ground_truth` to verify constants/config before assuming them.
```

#### For Cursor (`.cursorrules`)
Create `.cursorrules` in your project root:

```text
# GUARDIAN MCP INTEGRATION
You have access to Guardian tools. You MUST follow this strict protocol:

[Triggers]
- Plan/Feature request -> `start_engineering` (NEVER skip this)
- Code Edit -> `get_decision` (Check constraints first)
- API Change -> `get_api_contract` (Prevent breaking changes)

[Workflow]
1. Analyze: Use `search` and `get_context` first.
2. Gate: Use `start_engineering` for any task > 5 lines of code.
3. Verify: Use `ground_truth` for config values.
```

#### For Windsurf (`.windsurfrules`)
Create `.windsurfrules` in your project root:

```markdown
# Guardian Mode
Enable "Guardian Mode" for this project.

## Tool Usage
- **ALWAYS** use `start_engineering` for planning.
- **ALWAYS** check `get_decision` before editing critical components.
- **NEVER** hallucinate config; use `ground_truth`.

## Interaction
If I ask "what should I do?", check `list_active_features` and `get_next_step`.
```

### 5. Start Using Guardian

**Without AI integration file**: You must explicitly tell your AI to use Guardian:

```
"Use Guardian to scan this project"
"Use Guardian gates to implement user authentication"
```

**With AI integration file**: Guardian tools will be used automatically based on your trigger rules.

---

## What Guardian Does

### Incremental Code Intelligence
- **Automatic file monitoring**: Detects code changes instantly without manual rescans
- **17 language support**: Works across Rust, JavaScript, TypeScript, Python, Go, Java, C, C++, C#, PHP, Ruby, Swift, Elixir, Haskell, Lua, R, Bash
- **Incremental updates**: Only re-indexes changed files, not entire codebase

### Prevents Code Hallucination
- **Blocks duplicate functions**: AI can't rewrite `handleAuth` if it already exists in `src/auth.rs:42`
- **Forces code reuse**: AI must extend existing code instead of reinventing auth, caching, or rate limiting
- **Persistent memory**: Remembers what you built across sessions
- **Semantic search**: Find similar code and duplicates even without exact name matches

### Engineering Gates Workflow
A 3-gate system that forces AI to think before coding:

1. **Analysis Gate**: AI must find and document ALL existing types, models, API endpoints, and dependencies
2. **Planning Gate**: Guardian reviews the plan and rejects it if AI tries to recreate existing code
3. **Execution Gate**: Step-by-step implementation with progress tracking
4. **Completion**: Verifies all steps done, nothing forgotten

### Persistent Memory
- **Ground truth storage**: Confirmed config values, ports, package versions
- **API contracts**: Locks endpoint behavior with curl commands (prevents breaking changes)
- **Working set**: Tracks relevant files you're currently working on
- **Design decisions**: Records why something is complex (prevents premature optimization)

### Project Isolation
- Works with multiple huge codebases
- Scopes all queries to current project
- No cross-contamination between projects

---

## Usage Guide

> **💡 Remember**: You must tell your AI to use Guardian in every conversation. MCP tools only activate when explicitly requested.

### Recommended: Engineering Gates Workflow

For any new feature, **tell your AI to use the gated workflow**:

```
You: "Use Guardian gates to implement user profile export"
```

**What happens:**

1. **AI starts engineering process**
   ```
   AI calls: start_engineering(feature="user-profile-export", scope=["backend", "frontend"])
   ```

2. **Analysis Gate - AI finds existing code**
   ```
   AI searches for: similar functions, existing models, API patterns
   AI documents: ALL types, models, endpoints, dependencies
   AI submits: submit_analysis(...)
   ```

3. **Planning Gate - Guardian reviews**
   ```
   Guardian checks: Is AI reinventing existing code?
   Guardian validates: Security, error handling, existing code reuse
   Guardian scores: GARBAGE / POOR / GOOD / EXCELLENT
   Guardian rejects if: "Auth already exists in src/auth.rs, extend it instead"
   ```

4. **You approve the plan**
   ```
   Guardian presents plan file for review
   You approve: "Approve the plan"
   AI calls: approve_plan(feature_id="...")
   ```

5. **Execution Gate - Step-by-step implementation**
   ```
   AI gets: get_next_step() → "Step 1: Add export types"
   AI implements step
   AI reports: report_progress(step_completed="Add export types", files_modified=["types.ts"])
   AI gets: get_next_step() → "Step 2: Add API endpoint"
   ... continues until complete
   ```

**Benefits:**
- AI can't skip analysis or planning
- Guardian catches code duplication before it happens
- Progress tracked, resumable after interruptions
- Forces security and error handling

---

## Manual Tools (Advanced Usage)

### Search Your Codebase

```
You: "Use Guardian to find all caching-related functions"
AI: [calls search(query="cache", mode="search", fuzzy=true)]
Guardian: ✓ Found 3 matches: initCache (src/cache.rs:15), clearCache (src/cache.rs:42), getCacheStats (src/cache.rs:78)
```

### Find Similar Code

```
You: "Use Guardian to find code similar to my authentication function"
AI: [calls search(query="authenticate_user", mode="similar")]
Guardian: ✓ Found 2 similar functions: login_handler (similarity: 85%), verify_credentials (similarity: 72%)
```

### Get Function Context

```
You: "Use Guardian to show me the create_subscription function with context"
AI: [calls get_context(function="create_subscription", lines=30)]
Guardian: [Returns function code + 30 lines before/after + imports + dependencies + impact analysis]
```

### Store Verified Configuration

```
You: "Use Guardian to remember that server port is 3000"
AI: [calls ground_truth(action="set", key="server.port", value="3000", value_type="config")]
Guardian: ✓ Ground truth confirmed: server.port = 3000
```

### Lock API Contracts

**Tell Guardian to lock your API behavior:**

```
You: "Use Guardian to lock the /api/vehicles endpoint"
AI: [calls set_api_contract(...)]
Guardian: ✓ API contract locked for GET /api/vehicles
```

### Track Design Decisions

```
You: "Record why we use Razorpay"
AI: record_decision(
  component="payment_handler",
  reason="Using Razorpay for better async support and webhook handling"
)

Later...
AI: get_decision(component="payment_handler")
Guardian: Decision found: Using Razorpay for better async support...
```

### Find All References

```
You: "Where is AppError used?"
AI: search(query="AppError", mode="references", limit=50)
Guardian: Found 151 references across 23 files [shows file:line:snippet]
```

### Map Relationships

```
You: "What does create_subscription call and what calls it?"
AI: search(query="create_subscription", mode="relationships")
Guardian:
  Calls: [get_plan_limit, razorpay_service::create_subscription]
  Called by: [update_subscription, webhook_handler]
```

---

## Common Workflows

### Starting a New Feature

**Always tell AI to use Guardian:**

```
You: "Use Guardian gates to implement password reset feature"
```

What happens:
1. AI scans for existing auth code
2. Guardian reviews plan and blocks duplicates
3. You approve the plan
4. AI implements step-by-step with Guardian tracking progress

### Exploring Unfamiliar Codebase

```
You: "Use Guardian to find all authentication-related code"
AI: [calls search with various modes, get_context...]
Guardian: [Returns comprehensive auth code map across all 17 supported languages]
AI: "I found 12 auth-related functions. Here's the structure..."
```

**Note**: File watching automatically tracks changes as you explore, no manual rescans needed.

### Preventing Breaking Changes

```
You: "Use Guardian to lock the /api/users endpoint contract"
AI: [calls set_api_contract(...)]
Guardian: ✓ API contract locked
```

Later, when AI tries to modify the endpoint, Guardian will warn about breaking changes.

### Resuming After Interruption

```
You: "Use Guardian to resume the payment export feature"
AI: [calls list_active_features, resume_feature]
Guardian: [Returns full context: gate, progress %, next step, files modified]
AI: "You were at step 3/10. Next: Add export endpoint to router."
```

---

## Best Practices

> **🚨 #1 RULE**: Always start your prompt with **"Use Guardian"** or Guardian won't activate!

### DO:
- ✅ **Say "Use Guardian"** at the start of every task
- ✅ Use engineering gates for any non-trivial feature
- ✅ Let Guardian reject plans (it's catching duplicates)
- ✅ Store ground truth when AI confirms critical values
- ✅ Set API contracts for important endpoints
- ✅ Scan project first thing when starting work

### DON'T:
- ❌ **Forget to say "Use Guardian"** (AI won't invoke tools otherwise)
- ❌ Skip the analysis gate
- ❌ Override "function already exists" warnings without checking
- ❌ Work on multiple projects without setting context
- ❌ Ignore Guardian's plan rejections

---

## Available Tools Reference

**Total: 16 tools** (streamlined from 25 for better AI usability)

### Engineering Gates (Gated Workflow)
| Tool | Purpose |
|------|---------|
| `start_engineering` | Begin gated workflow for a feature |
| `submit_analysis` | Submit all types, models, endpoints, dependencies |
| `submit_plan` | Submit implementation plan (auto-reviewed) |
| `approve_plan` | User approves plan to begin execution |
| `get_next_step` | Get next implementation step |
| `report_progress` | Mark step complete, track progress |
| `resume_feature` | Resume after context loss or interruption |
| `list_active_features` | Show all in-progress features |

### Code Search & Analysis
| Tool | Purpose |
|------|---------|
| `scan_project` | Index entire codebase (automatic file watching starts after) |
| `search` | **Unified search tool** with 3 modes:<br>• `mode="search"` - Find functions by name (fuzzy/exact)<br>• `mode="references"` - Find all usages<br>• `mode="relationships"` - Map dependency graph |
| `get_context` | Get function code + surrounding context |

### Memory & Persistent State
| Tool | Purpose |
|------|---------|
| `ground_truth` | **Unified ground truth tool** with actions:<br>• `action="set"` - Store/update verified value<br>• `action="get"` - Retrieve verified value<br>• `action="delete"` - Remove entry<br>• `action="list"` - Show all stored values |
| `set_api_contract` | Lock API behavior with curl command |
| `get_api_contract` | Get stored API contract |
| `record_decision` | Store design decision with rationale |
| `get_decision` | Retrieve stored design decision |

### Project Management
| Tool | Purpose |
|------|---------|
| `context` | **Unified context tool** with actions:<br>• `action="remember"` - Add files to working set<br>• `action="get_files"` - Show tracked files<br>• `action="set_project"` - Switch projects<br>• `action="get_project"` - Show current project<br>• `action="list_projects"` - List all projects |

---

## Troubleshooting

### API Key Issues

**Error: "Missing API key"**

Add `GUARDIAN_API_KEY` to your MCP config:

```json
{
  "mcpServers": {
    "guardian": {
      "command": "npx",
      "args": ["-y", "@skyastrall/mcp-guardian@latest"],
      "env": {
        "GUARDIAN_API_KEY": "gd_your_api_key_here"
      }
    }
  }
}
```

Get your API key at **[guardianmcp.dev](https://guardianmcp.dev/)**

### Guardian Not Responding

1. Restart your AI tool (Claude Code, Cursor, etc.)
2. Check MCP config syntax is valid JSON
3. Verify API key starts with `gd_`

### "Function Already Exists" Warning

This is Guardian working correctly! It found duplicate code. Options:
1. Use the existing function (recommended)
2. Extend the existing function
3. If you really need a new function, use a different name

### Plan Rejected During Gates

Guardian is preventing code duplication. Review the rejection reason:
- "Auth already exists" → Extend existing auth code
- "Missing security section" → Add security considerations
- "No error handling" → Document error cases

---

## Support

- **Website**: [guardianmcp.dev](https://guardianmcp.dev/)
- **API Key**: Get yours at [guardianmcp.dev](https://guardianmcp.dev/)
- **Issues**: Found a bug? Open an issue on GitHub

---

## License

Proprietary - Closed Source SaaS Product

© 2025 SkyAstrall. All rights reserved.