KIA - Kaizen Intelligent Agent

KIA - Kaizen Intelligent Agent

Transforms Claude into a production-grade pair programmer by orchestrating best-in-class APIs (Morph, Chroma, DSPy) for iterative code evolution to 95%+ quality, semantic codebase search, package discovery across 3,000+ libraries, and pattern learning.

Category
访问服务器

README

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 License FastMCP

GitHub Repository


🎯 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:

# 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:


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:


4. learn_pattern - Collective Intelligence

Extract successful patterns from code evolutions and reuse them.

Example:

# 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

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

2. Install Dependencies

pip install -r requirements.txt

Or with uv (recommended):

pip install uv
uv pip install -r requirements.txt

3. Get API Keys

Morph API (code merging + semantic search):

Chroma Package Search (package discovery):

OpenRouter (GEPA/DSPy LLM backend):

  • Sign up: openrouter.ai
  • Export key: export OPENROUTER_API_KEY="sk-or-..."

4. Test Locally

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):

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

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:

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

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

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"

# 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"

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

"GEPA not available"

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

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:

Inspired by:

  • Addy Osmani's "70% Problem"
  • Zed's Agentic Engineering
  • Developer pain points from HN/Reddit research

📄 License

MIT License - See LICENSE file


🏢 Credits

KIA by Kaizen Labs

"Continuous improvement is better than delayed perfection." 🚀


📞 Support


Built with ❤️ by developers, for developers

推荐服务器

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 模型以安全和受控的方式获取实时的网络信息。

官方
精选