Skip to main content
Glama
Ash-Blanc

KIA - Kaizen Intelligent Agent

by Ash-Blanc
README.md
# KIA - Kaizen Intelligent Agent πŸš€

**Ultra-efficient 4-tool MCP server for production-grade pair programming**

> Smart orchestration of best-in-class APIs: Morph + Chroma + GEPA (DSPy)  
> Zero reinvention Β· Maximum leverage Β· 95%+ code quality in seconds

[![Version](https://img.shields.io/badge/version-0.3.0-blue.svg)](https://github.com/Ash-Blanc/kia-mcp-server)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![FastMCP](https://img.shields.io/badge/FastMCP-2.13+-orange.svg)](https://gofastmcp.com)

[GitHub Repository](https://github.com/Ash-Blanc/kia-mcp-server)

---

## 🎯 What is KIA?

KIA transforms Claude into a production-grade pair programmer by intelligently **orchestrating** the best code APIs available todayβ€”instead of reimplementing them.

**The Problem:** Most MCP servers reimplement basic primitives (search, merge, etc.) with poor performance.

**KIA's Solution:** Orchestrate world-class APIs with workflow-centric tools.

| Problem | KIA Solution | Powered By | Performance |
|---------|--------------|------------|-------------|
| **70% Code Quality** | Iterative evolution to 95%+ | GEPA (DSPy) + Morph fast-apply | ~6-12s |
| **Local Code Search** | Natural language search | Morph semantic search | ~1000ms |
| **Package Discovery** | Search 3,000+ packages | Chroma Package Search | ~1200ms |
| **No Learning** | Pattern extraction & reuse | KIA pattern library | instant |

---

## πŸ› οΈ Core Tools (4 Workflow-Centric)

### 1. `evolve_code` - Production-Ready Code Evolution

Solves the **70% problem** through intelligent, iterative improvement.

**How it works:**
1. GEPA (DSPy) generates multi-step reasoning trace + improvement plan
2. Morph fast-apply (10,500 tok/sec) applies each edit instantly
3. Quality validation across 5 dimensions (correctness, performance, security, readability, maintainability)
4. Iterates until 95%+ quality reached
5. Auto-learns successful patterns for future use

**Example:**
```python
# Input: 70% quality
def authenticate(username, password):
    user = db.query(f"SELECT * FROM users WHERE username='{username}'")
    if user and user.password == password:
        return True
    return False

# After evolve_code: 97% quality
# - SQL injection fixed with parameterized queries
# - Secure password hashing (SHA-256)
# - Constant-time comparison (timing attack protection)
# - Type hints and validation
# - Comprehensive docstrings
# Total time: ~8 seconds
```

**Powered by:**
- **GEPA**: State-of-the-art DSPy program evolution ([github.com/gepa-ai/gepa](https://github.com/gepa-ai/gepa))
- **Morph**: 10,500 tok/sec fast-apply ([morphllm.com](https://morphllm.com))

---

### 2. `search_local_codebase` - Natural Language Code Search

Search your project with plain English using Morph's two-stage semantic search.

**Example:**
```
User: "Search my codebase for JWT authentication logic"

KIA: [Morph two-stage retrieval: vector + GPU reranking]
     [Returns ranked results with relevance scores in ~1000ms]
```

**Features:**
- Natural language queries
- Two-stage retrieval (vector + rerank)
- Results in ~1000ms
- File paths + line numbers + relevance scores

**Requirements:**
- Code in a git repository
- Repository pushed to Morph (one-time setup)

---

### 3. `search_packages` - Discover Best Practices

Search 3,000+ public packages to learn from real implementations.

**Example:**
```
User: "Find rate limiting implementations from popular Python packages"

KIA: [Chroma searches: flask, fastapi, django, etc.]
     [Returns code examples + documentation links]
```

**Supported:**
- Python (PyPI)
- JavaScript/TypeScript (npm)
- Go (Go modules)
- Ruby (RubyGems)
- Java (Maven)
- And more...

**Powered by:**
- **Chroma**: 3,000+ indexed packages ([trychroma.com/package-search](https://trychroma.com/package-search))

---

### 4. `learn_pattern` - Collective Intelligence

Extract successful patterns from code evolutions and reuse them.

**Example:**
```python
# Pattern extracted from evolution:
# Name: "Type Safety + Validation"
# Confidence: 0.95
# Tags: ["type_hints", "validation", "security"]

# Before
def process(x):
    return x * 2

# After
def process(x: int) -> int:
    if not isinstance(x, int):
        raise TypeError("Expected int")
    return x * 2

# KIA learns this pattern and applies it to future evolutions automatically
```

---

## πŸ“ Prompts (9 Reusable Templates)

Prompts provide structured guidance for common workflows. **Use these first** to get the most out of KIA!

| Prompt | Parameters | Best For |
|--------|------------|----------|
| `quick_start` | None | First-time users, status check |
| `kia_usage_guide` | None | Complete documentation reference |
| `evolve_code_workflow` | `code`, `goal`, `focus_areas` | Step-by-step evolution guidance |
| `security_audit_prompt` | `code`, `language` | Security-focused code review |
| `refactor_legacy_code` | `code`, `original_language`, `modernize_to` | Modernizing old codebases |
| `performance_optimization` | `code`, `bottleneck_description` | Speed and efficiency improvements |
| `add_type_safety` | `code` | Adding type hints and validation |
| `debug_assistance` | `code`, `error_message`, `expected_behavior`, `actual_behavior` | Troubleshooting bugs |
| `compare_implementations` | `topic`, `packages` | Learning from multiple libraries |

### Example: Using Prompts

```
User: "Use the security_audit_prompt for this code:

def login(user, pwd):
    cur.execute(f"SELECT * FROM users WHERE name='{user}'")
    return cur.fetchone()[1] == pwd
"

KIA: [Returns structured security audit workflow]
     - Checklist of vulnerabilities to check
     - Recommended tool usage sequence
     - Common security fixes to apply
     - Step-by-step remediation guide
```

---

## πŸ“š Resources (10 Data Endpoints)

Resources provide read-only access to server state, configuration, and documentation.

| Resource URI | Description |
|-------------|-------------|
| `kia://stats/overview` | Server statistics and performance metrics |
| `kia://patterns/library` | All learned patterns in the library |
| `kia://patterns/{pattern_id}` | Specific pattern details (template) |
| `kia://evolution/history` | Recent code evolution history |
| `kia://api/status` | API configuration and health status |
| `kia://tools/catalog` | Complete tool documentation with examples |
| `kia://prompts/catalog` | All available prompts with descriptions |
| `kia://quality/{language}` | Language-specific quality guidelines (template) |
| `kia://tips/evolution` | Evolution best practices |
| `kia://tips/search` | Search optimization tips |

### Example: Reading Resources

```
User: "What's my KIA server status?"

[Read resource: kia://api/status]

{
  "apis": {
    "morph": {"configured": true, "performance": "10,500 tok/sec"},
    "chroma": {"configured": true, "packages_indexed": "3,000+"},
    "gepa_openrouter": {"configured": true, "model": "llama-3.1-70b"}
  },
  "overall_readiness": {"full_capability": true}
}
```

```
User: "Show me Python quality guidelines"

[Read resource: kia://quality/python]

{
  "type_hints": "Use typing module: List, Dict, Optional, Union",
  "docstrings": "Google or NumPy style with Args, Returns, Raises",
  "security": "parameterized queries, secrets module, input validation",
  "tools": ["mypy", "ruff", "black", "pytest"]
}
```

---

## πŸš€ Quick Setup

### Prerequisites

- Python 3.9+
- Git

### 1. Clone Repository

```bash
git clone https://github.com/Ash-Blanc/kia-mcp-server.git
cd kia-mcp-server
```

### 2. Install Dependencies

```bash
pip install -r requirements.txt
```

Or with uv (recommended):
```bash
pip install uv
uv pip install -r requirements.txt
```

### 3. Get API Keys

**Morph API** (code merging + semantic search):
- Sign up: [morphllm.com/dashboard](https://morphllm.com/dashboard)
- Export key: `export MORPH_API_KEY="sk-..."`

**Chroma Package Search** (package discovery):
- Sign up: [trychroma.com/package-search](https://trychroma.com/package-search)
- Export key: `export CHROMA_API_KEY="ck-..."`

**OpenRouter** (GEPA/DSPy LLM backend):
- Sign up: [openrouter.ai](https://openrouter.ai)
- Export key: `export OPENROUTER_API_KEY="sk-or-..."`

### 4. Test Locally

```bash
python server.py
# β†’ "πŸš€ KIA MCP Server starting..."
# β†’ "   Morph API: βœ… Available"
# β†’ "   Chroma API: βœ… Available"
# β†’ "   GEPA (OpenRouter): βœ… Available"
```

---

## πŸ”§ IDE Integration

### Claude Desktop (macOS/Windows)

Add to `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) or `%APPDATA%\Claude\claude_desktop_config.json` (Windows):

```json
{
  "mcpServers": {
    "kia": {
      "command": "python",
      "args": ["/absolute/path/to/kia-mcp-server/server.py"],
      "env": {
        "MORPH_API_KEY": "sk-...",
        "CHROMA_API_KEY": "ck-...",
        "OPENROUTER_API_KEY": "sk-or-..."
      }
    }
  }
}
```

**Restart Claude Desktop** β†’ KIA appears in your tool list βœ…

### Cursor / VS Code / Zed

Use FastMCP CLI for easy installation:

```bash
pip install fastmcp
fastmcp install cursor  # or vscode, zed
```

Or manually add to MCP settings with the same config format above.

---

## πŸ“– Usage Examples

### Recommended Workflow

1. **Start with `quick_start` prompt** - Check server status and see examples
2. **Use task-specific prompts** - Get structured guidance for your task
3. **Call tools with guidance** - Execute with context from prompts
4. **Check resources** - Monitor stats, review patterns

### Example 1: Evolve Legacy Code

```
User: "Use evolve_code on this function:

def login(user, pwd):
    cur.execute(f"SELECT * FROM users WHERE name='{user}'")
    row = cur.fetchone()
    return row and row[1] == pwd

Make it secure, typed, tested, production-ready."

KIA: 
[GEPA generates multi-step plan]
β†’ Step 1: Fix SQL injection
β†’ Step 2: Add password hashing
β†’ Step 3: Add type hints
β†’ Step 4: Add validation
β†’ Step 5: Add tests

[Morph applies each step at 10,500 tok/sec]
[Quality: 70% β†’ 97%]
[Time: ~8 seconds]

Result: Production-ready code with:
βœ… Parameterized SQL queries
βœ… Secure password hashing
βœ… Constant-time comparison
βœ… Full type annotations
βœ… Input validation
βœ… Comprehensive docstrings
βœ… Unit tests
```

### Example 2: Search Local Codebase

```
User: "Search my codebase for error handling patterns"

KIA:
[Morph semantic search: ~1000ms]

Results:
1. src/api/error_handler.py:45-67 (relevance: 0.94)
   - Custom exception hierarchy
   
2. src/utils/validators.py:23-38 (relevance: 0.87)
   - Input validation with custom errors
   
3. src/middleware/error_middleware.py:12-45 (relevance: 0.82)
   - Global error handler with logging
```

### Example 3: Search Packages

```
User: "Find JWT authentication implementations from popular Python packages"

KIA:
[Chroma searches PyPI packages]

Found in:
1. flask-jwt-extended (v4.5.2)
   - JWT token generation/validation
   - Refresh token support
   - File: jwt_manager.py:89-145

2. django-rest-framework-simplejwt (v5.2.2)
   - JWT authentication backend
   - Token blacklisting
   - File: authentication.py:23-78

3. fastapi-jwt-auth (v0.9.0)
   - Dependency injection pattern
   - Async JWT validation
   - File: auth_jwt.py:112-167
```

### Example 4: Learn Pattern

```
User: "This evolution was successful - learn from it:

Before:
def fetch_data(url):
    return requests.get(url).json()

After:
def fetch_data(url: str, timeout: int = 30) -> dict:
    try:
        response = requests.get(url, timeout=timeout)
        response.raise_for_status()
        return response.json()
    except requests.RequestException as e:
        logger.error(f"Failed to fetch {url}: {e}")
        raise

Improvement: Added error handling, timeouts, logging"

KIA:
[Extracts pattern: "Robust HTTP Requests"]
[Stores in pattern library]
[Tags: error_handling, timeouts, logging, http]
[Confidence: 0.92]

βœ… Pattern learned! Will apply to similar code in future evolutions.
```

### Example 5: Use Prompts for Structured Workflows

```
User: "I need to optimize this slow function"

[Get prompt: performance_optimization with code and bottleneck_description]

KIA Returns:
# Performance Optimization Workflow

## Code to Optimize:
[your code]

## Performance Analysis Checklist:
- Algorithm Complexity: O(nΒ²) β†’ O(n log n)?
- Caching opportunities
- Async I/O potential
- Batch operations

## Recommended Tool Usage:
1. search_packages(query="caching memoization", packages=["cachetools"])
2. evolve_code(code=..., quality_threshold=0.95)
3. search_local_codebase(query="similar performance patterns")

## Quick Wins:
- Replace list.append() with comprehensions
- Use set() for membership testing
- Add @lru_cache to pure functions
```

---

## πŸ—οΈ Architecture Philosophy

### Why External APIs?

**Anti-pattern:** Reimplementing semantic search, code merging, etc.

**KIA's approach:** Orchestrate best-in-class APIs.

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚     KIA MCP SERVER (Orchestrator)           β”‚
β”‚                                             β”‚
β”‚  4 workflow-centric tools:                 β”‚
β”‚  β€’ evolve_code                             β”‚
β”‚  β€’ search_local_codebase                   β”‚
β”‚  β€’ search_packages                         β”‚
β”‚  β€’ learn_pattern                           β”‚
β”‚                                             β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         ↓               ↓               ↓
   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
   β”‚  GEPA    β”‚    β”‚  Morph   β”‚    β”‚  Chroma  β”‚
   β”‚  (DSPy)  β”‚    β”‚ 10,500   β”‚    β”‚  3,000+  β”‚
   β”‚Evolution β”‚    β”‚ tok/sec  β”‚    β”‚Packages  β”‚
   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

**Benefits:**
1. **Performance:** Morph's 10,500 tok/sec vs. our ~100 tok/sec
2. **Quality:** GEPA's multi-step reasoning vs. simple prompts
3. **Scale:** Chroma's 3,000+ packages vs. our handful
4. **Maintenance:** They handle updates, improvements, scaling
5. **Cost:** Shared infrastructure vs. running our own

**What KIA Adds:**
- βœ… Smart orchestration (evolution workflow)
- βœ… Pattern learning (collective intelligence)
- βœ… Developer experience (workflow-centric tools)
- βœ… MCP protocol integration

---

## πŸ“Š Stats & Monitoring

Check KIA's performance via resources:

**Read `kia://stats/overview`:**

```json
{
  "total_evolutions": 42,
  "successful_evolutions": 39,
  "success_rate": 0.93,
  "patterns_learned": 15,
  "gepa_evolutions": 38,
  "morph_merges": 127,
  "chroma_searches": 8,
  "morph_searches": 12
}
```

**Read `kia://evolution/history`:**
```json
{
  "evolution_history": {
    "total_evolutions": 42,
    "recent_evolutions": [...],
    "summary": {
      "average_iterations": 7.3,
      "average_improvement": 0.24,
      "gepa_usage_rate": 0.91
    }
  }
}
```

---

## πŸ§ͺ Testing

Run the test suite:

```bash
python test_usability.py
```

Tests validate:
- βœ… All 4 core tools functional
- βœ… API integrations working
- βœ… Quality metrics calculation
- βœ… Pattern learning system

---

## πŸ”§ Troubleshooting

### "Morph API not configured"

```bash
# Check if key is set
echo $MORPH_API_KEY

# If empty, set it
export MORPH_API_KEY="your-key-here"

# Restart KIA
python server.py
```

### "Chroma Package Search requires API key"

```bash
export CHROMA_API_KEY="your-key-here"
python server.py
```

### "GEPA not available"

```bash
export OPENROUTER_API_KEY="your-key-here"
python server.py
```

### Evolution not improving quality

**Possible causes:**
1. Code is already high quality
2. No clear improvement path
3. API rate limits

**Solutions:**
- Check API quotas
- Review quality metrics
- Try with different code

---

## πŸ—ΊοΈ Roadmap

### Current (v0.3.0) βœ…
- βœ… GEPA (DSPy) integration for code evolution
- βœ… Morph fast-apply + semantic search
- βœ… Chroma Package Search integration
- βœ… Pattern learning system
- βœ… FastMCP 2.13+ framework

### Next (v0.4.0)
- [ ] Persistent pattern storage (disk-based)
- [ ] Pattern embeddings + semantic matching
- [ ] Multi-file evolution support
- [ ] Real-time quality visualization
- [ ] Self-evolution workflow (server evolves itself)

### Future (v1.0.0)
- [ ] Team collaboration features
- [ ] Custom pattern libraries
- [ ] Analytics dashboard
- [ ] CI/CD integration
- [ ] VS Code extension

---

## 🀝 Contributing

We welcome contributions! Priority areas:

- **GEPA/DSPy improvements** - Better reasoning chains
- **Pattern matching** - Semantic pattern search
- **Documentation** - More examples and guides
- **Test coverage** - Expand test suite
- **API integrations** - New code/search APIs

### Development Setup

```bash
git clone https://github.com/Ash-Blanc/kia-mcp-server.git
cd kia-mcp-server
pip install -r requirements.txt
python test_usability.py
```

---

## πŸ“š References

**Powered by:**
- [GEPA (DSPy Evolution)](https://github.com/gepa-ai/gepa) - State-of-the-art program evolution
- [Morph](https://morphllm.com) - Fast code merging & semantic search
- [Chroma](https://trychroma.com) - Package search API
- [FastMCP](https://gofastmcp.com) - MCP framework
- [OpenRouter](https://openrouter.ai) - LLM API gateway

**Inspired by:**
- Addy Osmani's "70% Problem"
- Zed's Agentic Engineering
- Developer pain points from HN/Reddit research

---

## πŸ“„ License

MIT License - See [LICENSE](LICENSE) file

---

## 🏒 Credits

**KIA** by [Kaizen Labs](https://github.com/Ash-Blanc)

*"Continuous improvement is better than delayed perfection."* πŸš€

---

## πŸ“ž Support

- **Issues**: [GitHub Issues](https://github.com/Ash-Blanc/kia-mcp-server/issues)
- **Discussions**: [GitHub Discussions](https://github.com/Ash-Blanc/kia-mcp-server/discussions)
- **Email**: support@kaizenlabs.dev (coming soon)

---

**Built with ❀️ by developers, for developers**