iflow-mcp_normaltusker_kotlin_mcp_server 2.1.0
Enterprise Kotlin Android MCP Server with AI-powered development tools
Requires Python: >=3.8
Keywords: mcp, model-context-protocol, kotlin, android, development, ai, code-generation, jetpack-compose, mvvm, gradle

# Enterprise Kotlin Android MCP Server

A comprehensive Model Context Protocol (MCP) server that provides AI agents with enterprise-grade access to Kotlin-based Android development projects. This server enables context-aware assistance with advanced security, privacy compliance, AI integration, and comprehensive development tools.

---

## 📋 **Revision History**

### **Version 2.1** *(Current - August 2025)*
**Enhanced Release: Unified Intelligent Server**

#### 🎯 **Latest Improvements**
- **🧠 Intelligent Tool Management**: All 27 tools now use intelligent proxy system with LSP-like capabilities
- **🔄 Server Consolidation**: Unified into single `kotlin_mcp_server.py` with enhanced architecture
- **📁 Clean Architecture**: Archived redundant server versions for cleaner project structure
- **⚡ Enhanced Tool Exposure**: Complete tool suite properly exposed through intelligent management system
- **🛠️ Improved Tool Routing**: Smart delegation between native implementations and intelligent proxies

#### 🔧 **Architectural Changes**
- **Unified Server**: Single `kotlin_mcp_server.py` replaces multiple server versions
- **Intelligent Proxy System**: Tools without full implementations use smart proxies with AI enhancement
- **Clean File Structure**: Legacy servers archived in `archive/legacy-servers/`
- **Enhanced Tool Manager**: Integration with `IntelligentMCPToolManager` for advanced capabilities
- **Complete Tool Coverage**: All 32 tools properly exposed and functional

#### 📊 **Tool Implementation Status**
- **Fully Implemented**: 6 tools (format_code, run_lint, generate_docs, create_compose_component, setup_mvvm_architecture, security_hardening)
- **Legacy Integration**: 3 core tools (create_kotlin_file, gradle_build, analyze_project)
- **Intelligent Proxies**: 23 tools with smart fallback implementations
- **Total Available**: 32 tools with comprehensive Android development coverage

### **Version 2.0** *(August 2025)*
**Major Release: AI-Enhanced Modular Architecture**

#### 🎯 **Key Improvements**
- **🤖 AI Integration**: Transformed from template generator to AI-powered development assistant
- **🏗️ Modular Architecture**: Refactored monolithic structure into 6 specialized modules 
- **🌍 Dynamic Configuration**: Eliminated all hardcoded paths for cross-platform portability
- **⚡ Enhanced Tools**: Expanded from 30 to 31 tools with AI-enhanced implementations
- **🛡️ Security Hardening**: Added configurable audit trails and compliance monitoring
- **📦 Zero-Config Setup**: Intelligent installer with automatic environment detection

#### 🔧 **Technical Changes**
- **Modular Design**: Split into `ai/`, `android/`, `gradle/`, `security/`, `testing/`, `utils/` modules
- **AI-Powered Code Generation**: Leverages calling LLM for production-ready code (no TODOs)
- **Environment Variable Support**: All configurations now use dynamic environment variables
- **Cross-Platform Paths**: Universal `~` notation replaces OS-specific hardcoded paths
- **Enhanced Error Handling**: Comprehensive validation and graceful failure recovery
- **Performance Optimization**: Streamlined tool execution with better resource management

#### 📊 **Migration Impact**
- **Tools**: 30 → 32 tools (107% feature parity + enhancements)
- **File Size**: Optimized modular structure vs. monolithic approach
- **Configuration**: Zero manual path configuration required
- **Compatibility**: Maintains full backward compatibility with existing setups

### **Version 1.0** *(Legacy - Pre-August 2025)*
**Initial Release: Template-Based Code Generator**
- ✅ Basic MCP server with 30 tools
- ✅ Template-based Kotlin/Android code generation
- ✅ Manual configuration with hardcoded paths
- ✅ Monolithic architecture
- ✅ Basic security and compliance features

---

## 🌟 **Enterprise Features Overview**

### 🔒 **Security & Privacy Compliance**
- **GDPR Compliance** - Complete implementation with consent management, data portability, right to erasure
- **HIPAA Compliance** - Healthcare-grade security with audit logging, access controls, encryption
- **Data Encryption** - AES-256 encryption with PBKDF2 key derivation for sensitive data
- **Audit Trails** - Comprehensive logging with compliance flags and security event tracking
- **Privacy by Design** - Built-in privacy protection for all operations

### 🤖 **AI/ML Integration**
- **Local LLM Support** - Ollama, LocalAI, and self-hosted transformers
- **External LLM APIs** - OpenAI GPT-4, Anthropic Claude, custom endpoints
- **AI-Powered Code Analysis** - Security, performance, and complexity analysis
- **Intelligent Code Generation** - Context-aware Kotlin/Android code creation
- **ML Model Integration** - TensorFlow Lite, ONNX, PyTorch Mobile for Android apps

### 📁 **Advanced File Management**
- **Enterprise File Operations** - Backup, restore, sync, encrypt, decrypt with audit trails
- **Real-time Synchronization** - File system watchers with automatic sync
- **Cloud Storage Integration** - AWS S3, Google Cloud, Azure with end-to-end encryption
- **Smart File Classification** - Automatic sensitive data detection and encryption
- **Version Control** - Git-aware operations with conflict resolution

### 🌐 **External API Integration**
- **Comprehensive Auth Support** - API Keys, OAuth 2.0, JWT, Basic Auth
- **Security Features** - Rate limiting, request logging, response validation
- **Real-time Monitoring** - API usage metrics, performance tracking, cost analysis
- **Compliance Validation** - GDPR/HIPAA compliant API handling

### 🏗️ **Advanced Android Development**
- **Architecture Patterns** - MVVM, Clean Architecture, Dependency Injection
- **Modern UI Development** - Jetpack Compose, custom views, complex layouts
- **Database Integration** - Room with encryption, migration handling
- **Network Layer** - Retrofit, GraphQL, WebSocket support
- **Testing Framework** - Comprehensive test generation and execution

---

## 🚀 **Quick Start & Installation**

### ✨ **Upgrade to V2.0 Highlights**

**🤖 AI-Enhanced Development**: Now leverages your AI assistant for production-ready code generation instead of basic templates!

**Before (V1.0):**
- ❌ Template-based code with TODO placeholders
- ❌ Manual path editing in config files
- ❌ Monolithic architecture (single large file)
- ❌ Hardcoded paths and user-specific configurations
- ❌ 30 basic tools with limited AI integration

**After (V2.0):**
- ✅ **AI-Powered Code Generation**: Complete, context-aware implementations
- ✅ **Zero-Configuration Setup**: `python3 install.py` handles everything
- ✅ **Modular Architecture**: Clean, maintainable 6-module structure
- ✅ **Dynamic Configuration**: Cross-platform with environment variables
- ✅ **31 Enhanced Tools**: AI-integrated with intelligent error handling

### 📋 **System Requirements**

- **Python 3.8+** (3.9+ recommended)
- **pip** (Python package manager)
- **Git** (for cloning repository)
- **IDE with MCP support** (VS Code, JetBrains IDEs, Claude Desktop)

### 🔧 **Installation Steps**

#### **1. Clone Repository**
```bash
git clone <your-repo-url>
cd kotlin-mcp-server
```

#### **2. Automated Installation & Configuration**

The project includes an enhanced installation script that handles all configuration automatically:

```bash
# Interactive installation (recommended for first-time users)
python3 install.py

# Non-interactive installation with specific configuration
python3 install.py [install_type] [project_path] [server_name] [use_env_vars]

# Show all available options
python3 install.py --help
```

**Installation Types:**
- `1` - **Portable**: Run directly from project directory
- `2` - **System**: Install command to PATH (`kotlin-android-mcp`)  
- `3` - **Module**: Enable `python -m kotlin_mcp_server`

**Configuration Examples:**

```bash
# Interactive setup (asks for your preferences)
python3 install.py 1

# Portable with your Android project path (replace with actual path)
python3 install.py 1 ~/AndroidStudioProjects/MyApp

# System installation with dynamic environment variables
python3 install.py 2 none my-android-server true

# Module installation with custom server name
python3 install.py 3 /path/to/project kotlin-dev false
```

**What the installer does:**
- ✅ **Installs all Python dependencies** from `requirements.txt`
- ✅ **Creates platform-specific config files** (Claude, VS Code, generic)
- ✅ **Sets up proper file permissions** for scripts
- ✅ **Configures environment variables** based on your choices
- ✅ **Eliminates manual path updates** in configuration files
- ✅ **Provides clear integration instructions** for your setup

#### **3. Manual Installation (Alternative)**

If you prefer manual installation:

```bash
# Install core dependencies
pip install -r requirements.txt

# Optional: Install AI/ML dependencies for advanced features
pip install openai anthropic transformers torch

# Verify installation
python3 -c "import kotlin_mcp_server; print('✅ Installation successful')"
```

**Key Dependencies Installed:**
- **Core MCP:** `python-dotenv`, `pydantic`
- **Security:** `cryptography`, `bcrypt`, `PyJWT`
- **Database:** `aiosqlite`, `sqlalchemy`
- **HTTP Clients:** `aiohttp`, `httpx`
- **File Management:** `aiofiles`, `watchdog`
- **Testing:** `pytest`, `pytest-asyncio`, `coverage`
- **Code Quality:** `black`, `flake8`, `pylint`, `mypy`
- **Security Tools:** `bandit`, `safety`

#### **4. V2.0 Architecture & Tool Enhancements**

**🏗️ Modular Architecture Design**

The V2.0 release introduces a clean, maintainable modular structure:

```
kotlin-mcp-server/
├── kotlin_mcp_server.py      # Main server (32 AI-enhanced tools)
├── ai/
│   ├── llm_integration.py    # AI assistant integration
│   └── code_enhancement.py   # AI-powered code generation
├── android/
│   ├── project_manager.py    # Project structure management  
│   └── manifest_utils.py     # Android manifest operations
├── gradle/
│   ├── build_system.py       # Gradle build automation
│   └── dependency_manager.py # Dependency resolution
├── security/
│   ├── compliance.py         # GDPR/HIPAA compliance
│   └── encryption.py         # Data protection
├── testing/
│   └── test_generator.py     # Automated test creation
└── utils/
    ├── file_operations.py    # Enhanced file management
    └── security.py           # Audit trails & logging
```

**🤖 AI-Enhanced Tool Capabilities**

| Tool Category | V1.0 (Templates) | V2.0 (AI-Enhanced) |
|---------------|-------------------|-------------------|
| **Code Generation** | Basic templates with TODOs | Production-ready, context-aware implementations |
| **Architecture Patterns** | Skeleton code | Complete MVVM, Clean Architecture patterns |
| **UI Components** | Static layouts | Dynamic Jetpack Compose with business logic |
| **Database Operations** | Schema templates | Full Room implementation with migrations |
| **Testing** | Test stubs | Comprehensive test suites with edge cases |
| **Security** | Basic validation | Enterprise-grade security with compliance |

**⚡ Performance & Reliability Improvements**

- **31 Tools** (vs 30 in V1.0) with enhanced AI integration
- **Error Recovery**: Graceful handling of AI service interruptions
- **Context Awareness**: Tools understand project structure and requirements
- **Resource Optimization**: Efficient memory usage and faster execution
- **Cross-Platform Support**: Universal configuration system

#### **5. IDE Integration Setup**

After installation, the script generates ready-to-use configuration files:

- **`mcp_config_claude.json`** - For Claude Desktop
- **`mcp_config_vscode.json`** - For VS Code and Cursor  
- **`mcp_config.json`** - For other MCP clients

**Integration Instructions:**

🔹 **Claude Desktop**: Copy content from `mcp_config_claude.json` to:
   - **Mac**: `~/Library/Application Support/Claude/claude_desktop_config.json`
   - **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
   - **Linux**: `~/.config/claude/claude_desktop_config.json`

🔹 **VS Code/Cursor**: Add to your VS Code `settings.json`:
   ```json
   {
     "mcp.server.configFiles": [
       "/absolute/path/to/mcp_config_vscode.json"
     ]
   }
   ```

🔹 **Other IDEs**: Use `mcp_config.json` with your MCP client

#### **5. Environment Configuration (Advanced)**

For advanced users who need custom environment setup:
Create a `.env` file in the project root (only needed for advanced configurations):

```bash
# Copy the example file and customize
cp .env.example .env

# Edit with your settings
nano .env  # or your preferred editor
```

**Optional Variables:**
```bash
# Security (generate strong password)
MCP_ENCRYPTION_PASSWORD=$(openssl rand -base64 32)
COMPLIANCE_MODE=gdpr,hipaa

# Optional: AI Integration
OPENAI_API_KEY=your-openai-api-key-here
ANTHROPIC_API_KEY=your-anthropic-api-key-here
```

**💡 Note**: The installation script automatically configures project paths and server settings, so manual environment configuration is only needed for advanced features like AI integration or custom security settings.

#### **6. Install Required IDE Extensions/Plugins**
See the [Plugin Requirements](#-required-pluginsextensions) section below for IDE-specific extensions.

#### **7. Test Installation**
```bash
# Test the server with your configured setup
# If you used a fixed project path during installation:
python3 kotlin_mcp_server.py

# If you're using dynamic/environment variables:
python3 kotlin_mcp_server.py /path/to/android/project

# For system installation:
kotlin-android-mcp

# For module installation:
python3 -m kotlin_mcp_server

# Validate configuration (optional)
python3 validate_config.py

# Run comprehensive tests (optional)
python test_mcp_comprehensive.py

# Test VS Code bridge server (optional)
python3 vscode_bridge.py &
sleep 2
curl http://localhost:8080/health
# Should return: {"status": "healthy", ...}
kill %1  # Stop background bridge server
```

### ⚡ **Quick Setup Commands**
```bash
# Complete setup with one command (interactive)
python3 install.py

# Quick setup for development environment
make setup-dev

# Quick validation
make dev-check

# Full quality pipeline
make ci

# Test VS Code bridge server (optional)
python3 vscode_bridge.py --test-mode
```

### 🎯 **Installation Summary**

The enhanced installation process has **eliminated the need for manual configuration**:

✅ **Before (Manual)**: Users had to manually edit config files, find paths, update environment variables  
✅ **After (Automated)**: One command creates everything ready-to-use

**Key Improvements:**
- 🚀 **Zero Manual Configuration**: No more path updates or variable editing
- 🎛️ **Interactive & Non-Interactive**: Works in both modes for all users
- 🔧 **Platform-Specific Configs**: Generates optimized files for each IDE/client
- 📋 **Clear Instructions**: Provides exact integration steps for your setup
- ✨ **Smart Defaults**: Handles environment variables intelligently

### 🐳 **Docker Deployment (Optional)**

For containerized deployment, the project includes comprehensive Docker support:

#### **Quick Docker Setup**

```bash
# 1. Validate Docker configuration
python3 validate_docker.py

# 2. Build and run with the setup script
./docker-setup.sh build
./docker-setup.sh start

# 3. Or use Docker Compose directly
docker-compose up -d kotlin-mcp-server
```

#### **Docker Features**

- 🔒 **Security**: Non-root user, minimal attack surface
- 📦 **Optimized**: Multi-stage builds, layer caching
- 🔍 **Health Checks**: Automatic container health monitoring
- 🛠️ **Development**: Volume mounts for live development
- 🚀 **Production**: Daemon mode for production deployment

#### **Available Commands**

```bash
./docker-setup.sh build              # Build the image
./docker-setup.sh start              # Interactive development
./docker-setup.sh daemon [path]      # Production daemon mode
./docker-setup.sh logs               # View container logs
./docker-setup.sh shell              # Open container shell
./docker-setup.sh test               # Run tests in container
./docker-setup.sh clean              # Clean up resources
```

**For detailed Docker setup instructions, see [DOCKER_SETUP.md](DOCKER_SETUP.md)**

---

## 🎯 **Prove-It: Generate Real Android Apps**

**Ready to see the system generate complete, production-ready Android apps?** Follow these steps to witness the full E2E workflow:

### 🚀 **Quick Start: Generate Your First App**

```bash
# 1. Build the Kotlin sidecar (creates fat JAR)
make sidecar

# 2. Generate complete Android app with all features
make e2e

# 3. Your APK appears here:
ls -la e2e/sampleapp/app/build/outputs/apk/debug/app-debug.apk
```

**What you get:**
- ✅ **Complete Gradle project** (Kotlin, Compose, Hilt, MVVM)
- ✅ **Working Android app** with HomeScreen + DetailsScreen
- ✅ **Room database** with entities and DAOs
- ✅ **Retrofit network layer** with API service
- ✅ **Unit tests** that pass (Robolectric + JVM tests)
- ✅ **APK ready to install** on device/emulator

### 🔧 **Available Commands**

```bash
# Build Kotlin sidecar JAR
make sidecar

# Generate complete Android app
make e2e

# Format and optimize code
make fix

# Run detekt static analysis
make detekt

# Run spotless code formatting check
make spotless

# Clean all artifacts
make clean
```

### 📊 **Generated App Features**

The generated `e2e/sampleapp` includes:

**🏗️ Architecture:**
- MVVM pattern with ViewModels
- Hilt dependency injection
- Clean Architecture principles

**🎨 UI/UX:**
- Jetpack Compose screens
- Material3 design
- Navigation between screens

**💾 Data Layer:**
- Room database with entities
- Repository pattern
- Migration skeletons

**🌐 Network:**
- Retrofit API client
- OkHttp interceptors
- Error handling

**🧪 Testing:**
- Unit tests for ViewModels
- DAO tests with Robolectric
- API service tests

**📱 Build:**
- Debug APK generation
- Lint/format checks
- Gradle build optimization

### ⚙️ **Environment Variables**

```bash
# Sidecar configuration
MCP_SIDECAR_CMD=["java", "-jar", "kotlin-sidecar/build/libs/kotlin-sidecar.jar"]

# Performance tuning
MCP_API_TIMEOUT_MS=3000
MCP_RATE_LIMIT_QPS=10

# Build settings
ANDROID_SDK_ROOT=/path/to/android/sdk
JAVA_HOME=/path/to/jdk17
```

### 🔍 **Troubleshooting**

**Gradle build fails:**
```bash
# Ensure Android SDK is installed and ANDROID_SDK_ROOT is set
export ANDROID_SDK_ROOT=/path/to/android/sdk

# Clean and rebuild
make clean && make e2e
```

**Sidecar connection issues:**
```bash
# Check if JAR was built
ls -la kotlin-sidecar/build/libs/kotlin-sidecar.jar

# Test sidecar directly
java -jar kotlin-sidecar/build/libs/kotlin-sidecar.jar
```

**APK not generated:**
```bash
# Check build logs
cd e2e/sampleapp && ./gradlew assembleDebug --info

# Ensure JDK 17 is used
java -version  # Should show Java 17
```

### 📈 **Performance Benchmarks**

The system is optimized for:
- **Sidecar startup**: < 2 seconds
- **Code generation**: < 5 seconds per component
- **Build time**: < 30 seconds for debug APK
- **Test execution**: < 10 seconds for unit tests

### 🎉 **Success Indicators**

When everything works correctly:
- ✅ `kotlin-sidecar.jar` builds successfully
- ✅ `e2e/sampleapp` directory created with full project
- ✅ `./gradlew assembleDebug` completes without errors
- ✅ APK file exists: `app/build/outputs/apk/debug/app-debug.apk`
- ✅ `./gradlew testDebugUnitTest` passes tests
- ✅ No TODO placeholders in generated code
- ✅ All lint/format checks pass

**🎯 The generated app is production-ready and can be opened in Android Studio immediately!**

---

## � **Migration from V1.0 to V2.0**

### **⚡ Quick Migration Steps**

If you have an existing V1.0 installation:

1. **Backup Current Setup**:
   ```bash
   # Backup your existing configuration
   cp mcp_config*.json ~/backup/
   ```

2. **Update to V2.0**:
   ```bash
   # Pull latest changes
   git pull origin main
   
   # Run V2.0 installer
   python3 install.py 1
   ```

3. **Verify Migration**:
   ```bash
   # Test the new modular architecture
   python3 -c "from kotlin_mcp_server import KotlinMCPServer; print('✅ V2.0 Ready!')"
   ```

### **🔍 What's Automatically Migrated**

- ✅ **All 30 original tools** preserved with enhanced AI capabilities
- ✅ **Configuration files** updated with dynamic environment variables
- ✅ **Project paths** converted to cross-platform format
- ✅ **Dependencies** updated to latest versions
- ✅ **Security settings** enhanced with new compliance features

### **⚠️ Migration Notes**

- **Backward Compatibility**: V2.0 maintains full compatibility with V1.0 project structures
- **Enhanced Output**: Code generation now produces complete implementations instead of templates
- **New Environment Variables**: Optional new configuration options (see `.env.example`)
- **Modular Structure**: Internal architecture improved (no user action needed)

---

## 🏗️ **Project Root Resolution Policy**

### **Overview**
All tools in the Kotlin MCP Server have been refactored to work exclusively on the user's project workspace, never on the MCP server's current working directory. This ensures safe, predictable tool behavior and prevents accidental modifications outside your project.

### **Path Resolution Priority**
Tools resolve the project root in this order:

1. **Explicit Input**: `project_root` or `projectRoot` parameter
2. **Environment Variables**: `PROJECT_PATH` or `WORKSPACE_PATH`
3. **IDE Metadata**: Workspace root from MCP client (VS Code, Cursor, etc.)
4. **Fail-Safe**: Tools will error rather than use server CWD

### **Input Synonyms**
Tools accept both camelCase and snake_case parameter names:

```json
// Both formats work identically
{
  "project_root": "/path/to/project",
  "file_path": "src/main.kt",
  "build_tool": "gradle",
  "skip_tests": false
}

{
  "projectRoot": "/path/to/project", 
  "filePath": "src/main.kt",
  "buildTool": "gradle",
  "skipTests": false
}
```

### **IDE Integration Defaults**
When using IDE extensions (VS Code, Cursor), tools automatically detect:

- **Workspace Root**: Active workspace directory
- **Active File**: Currently open file for file-based operations
- **Selection**: Text selection for refactoring operations

### **Security Safeguards**
- **Path Traversal Protection**: All file paths validated to be under project root
- **Server CWD Guard**: Runtime checks prevent accidental server directory operations
- **Audit Logging**: All tool operations logged with project context

### **Example Tool Calls**

**With Explicit Project Root:**
```json
{
  "tool": "buildAndTest",
  "input": {
    "project_root": "/Users/dev/MyAndroidApp",
    "buildTool": "gradle",
    "skipTests": false
  }
}
```

**With Environment Variable:**
```bash
export PROJECT_PATH=/Users/dev/MyAndroidApp
# Tool calls without project_root will use environment
```

**IDE Auto-Detection:**
```json
{
  "tool": "analyzeCodeQuality",
  "input": {
    "scope": "project",
    "ruleset": "all"
  }
}
// Uses active workspace automatically
```

### **Error Handling**
Tools provide clear errors when project root cannot be resolved:

```json
{
  "success": false,
  "error": "ProjectRootRequired: pass `project_root` or set env PROJECT_PATH",
  "error_type": "ProjectRootRequired"
}
```

---

## 📚 **Comprehensive Usage Guide**

### 🛠 **Complete Tool Reference**

The Kotlin MCP Server provides 31 comprehensive tools for Android development, organized by category:

#### **Core Development Tools**

##### 1. `gradle_build` - Build Android Projects
Executes Gradle build tasks for your Android project.

```json
{
  "name": "gradle_build",
  "arguments": {
    "task": "assembleDebug",
    "clean_build": false,
    "parallel": true
  }
}
```
**Parameters:**
- `task` (string): Gradle task to execute (e.g., "assembleDebug", "build", "test")
- `clean_build` (boolean, optional): Whether to clean before building
- `parallel` (boolean, optional): Enable parallel execution

**Usage Examples:**
```bash
# Build debug APK
{"name": "gradle_build", "arguments": {"task": "assembleDebug"}}

# Clean and build release
{"name": "gradle_build", "arguments": {"task": "assembleRelease", "clean_build": true}}

# Run all tests
{"name": "gradle_build", "arguments": {"task": "test"}}
```

##### 2. `run_tests` - Execute Test Suites
Runs unit tests, integration tests, or UI tests with comprehensive reporting.

```json
{
  "name": "run_tests",
  "arguments": {
    "test_type": "unit",
    "test_class": "UserRepositoryTest",
    "generate_report": true
  }
}
```
**Parameters:**
- `test_type` (string): "unit", "integration", "ui", or "all"
- `test_class` (string, optional): Specific test class to run
- `generate_report` (boolean, optional): Generate HTML test report

##### 3. `create_kotlin_file` - Generate Kotlin Files
Creates structured Kotlin files with proper package declaration and imports.

```json
{
  "name": "create_kotlin_file",
  "arguments": {
    "file_path": "src/main/kotlin/com/example/User.kt",
    "class_name": "User",
    "class_type": "data_class",
    "properties": ["id: String", "name: String", "email: String"],
    "package_name": "com.example.model"
  }
}
```
**Parameters:**
- `file_path` (string): Relative path for the new file
- `class_name` (string): Name of the main class
- `class_type` (string): "class", "data_class", "sealed_class", "object", "interface"
- `properties` (array, optional): List of properties for data classes
- `package_name` (string, optional): Package declaration

##### 4. `create_layout_file` - Generate XML Layouts
Creates Android XML layout files with proper structure.

```json
{
  "name": "create_layout_file",
  "arguments": {
    "file_path": "src/main/res/layout/activity_main.xml",
    "layout_type": "activity",
    "root_element": "LinearLayout",
    "include_common_attributes": true
  }
}
```

##### 5. `analyze_project` - Project Analysis
Provides comprehensive analysis of your Android project structure, dependencies, and architecture.

```json
{
  "name": "analyze_project",
  "arguments": {
    "analysis_type": "architecture",
    "include_dependencies": true,
    "check_best_practices": true
  }
}
```
**Analysis Types:**
- `architecture`: Overall project structure and patterns
- `dependencies`: Gradle dependencies and versions
- `security`: Security vulnerabilities and best practices
- `performance`: Performance bottlenecks and optimizations

##### 6. `format_code` - Code Formatting
Formats Kotlin code according to style guidelines.

```json
{
  "name": "format_code",
  "arguments": {
    "file_path": "src/main/kotlin/MainActivity.kt",
    "style_guide": "ktlint"
  }
}
```

##### 7. `run_lint` - Static Code Analysis
Runs lint analysis to detect code issues.

```json
{
  "name": "run_lint",
  "arguments": {
    "lint_tool": "detekt",
    "fail_on_warnings": false,
    "generate_report": true
  }
}
```

##### 8. `generate_docs` - Documentation Generation
Generates project documentation in various formats.

```json
{
  "name": "generate_docs",
  "arguments": {
    "doc_type": "kdoc",
    "output_format": "html",
    "include_private": false
  }
}
```

#### **UI Development Tools**

##### 9. `create_compose_component` - Jetpack Compose Components
Generates Jetpack Compose UI components with best practices.

```json
{
  "name": "create_compose_component",
  "arguments": {
    "component_name": "UserCard",
    "component_type": "composable",
    "file_path": "src/main/kotlin/ui/components/UserCard.kt",
    "parameters": [
      "user: User",
      "onClick: () -> Unit"
    ],
    "include_preview": true,
    "material_design": "material3"
  }
}
```
**Component Types:**
- `composable`: Standard composable function
- `stateful`: Composable with internal state
- `stateless`: Pure UI composable
- `layout`: Layout composable with children

##### 10. `create_custom_view` - Custom Android Views
Creates custom View classes with proper lifecycle management.

```json
{
  "name": "create_custom_view",
  "arguments": {
    "view_name": "CircularProgressView",
    "base_class": "View",
    "file_path": "src/main/kotlin/ui/views/CircularProgressView.kt",
    "custom_attributes": [
      {"name": "progressColor", "type": "color"},
      {"name": "strokeWidth", "type": "dimension"}
    ]
  }
}
```

#### **Architecture & Pattern Tools**

##### 11. `setup_mvvm_architecture` - MVVM Implementation
Sets up complete MVVM architecture with ViewModel, Repository, and UI layers.

```json
{
  "name": "setup_mvvm_architecture",
  "arguments": {
    "feature_name": "UserProfile",
    "package_name": "com.example.userprofile",
    "include_repository": true,
    "include_use_cases": true,
    "state_management": "compose"
  }
}
```
**Generated Files:**
- ViewModel with state management
- Repository with data source abstraction
- Use cases for business logic
- UI composables or fragments
- State classes and sealed classes for events

##### 12. `setup_dependency_injection` - DI Framework Setup
Configures dependency injection using Hilt or Dagger.

```json
{
  "name": "setup_dependency_injection",
  "arguments": {
    "di_framework": "hilt",
    "modules": ["DatabaseModule", "NetworkModule", "RepositoryModule"],
    "application_class": "MyApplication"
  }
}
```

##### 13. `setup_room_database` - Database Setup
Creates Room database implementation with entities, DAOs, and migrations.

```json
{
  "name": "setup_room_database",
  "arguments": {
    "database_name": "AppDatabase",
    "entities": [
      {
        "name": "User",
        "fields": [
          {"name": "id", "type": "String", "primaryKey": true},
          {"name": "name", "type": "String"},
          {"name": "email", "type": "String"}
        ]
      }
    ],
    "version": 1,
    "enable_encryption": true
  }
}
```

##### 14. `setup_retrofit_api` - Network Layer
Sets up Retrofit API interfaces with proper error handling and interceptors.

```json
{
  "name": "setup_retrofit_api",
  "arguments": {
    "base_url": "https://api.example.com/",
    "endpoints": [
      {
        "name": "getUser",
        "method": "GET",
        "path": "users/{id}",
        "response_type": "User"
      }
    ],
    "include_interceptors": ["logging", "auth", "retry"],
    "enable_cache": true
  }
}
```

#### **Security & Compliance Tools**

##### 15. `encrypt_sensitive_data` - Data Encryption
Encrypts sensitive data using industry-standard encryption.

```json
{
  "name": "encrypt_sensitive_data",
  "arguments": {
    "data": "Patient: John Doe, SSN: 123-45-6789",
    "data_type": "phi",
    "compliance_level": "hipaa",
    "encryption_algorithm": "AES-256"
  }
}
```

##### 16. `implement_gdpr_compliance` - GDPR Implementation
Implements complete GDPR compliance framework.

```json
{
  "name": "implement_gdpr_compliance",
  "arguments": {
    "package_name": "com.example.app",
    "features": [
      "consent_management",
      "data_portability",
      "right_to_erasure",
      "privacy_policy",
      "data_breach_notification"
    ],
    "supported_languages": ["en", "de", "fr"],
    "include_ui": true
  }
}
```
**Generated Components:**
- Consent management UI and logic
- Data export functionality
- User data deletion workflows
- Privacy policy templates
- Audit logging system

##### 17. `implement_hipaa_compliance` - HIPAA Implementation
Implements HIPAA-compliant security measures.

```json
{
  "name": "implement_hipaa_compliance",
  "arguments": {
    "package_name": "com.healthcare.app",
    "features": [
      "audit_logging",
      "access_controls",
      "encryption",
      "secure_messaging",
      "risk_assessment"
    ],
    "minimum_password_strength": "high",
    "session_timeout": 900
  }
}
```

##### 18. `setup_secure_storage` - Secure Data Storage
Configures encrypted storage for sensitive data.

```json
{
  "name": "setup_secure_storage",
  "arguments": {
    "storage_type": "room_encrypted",
    "package_name": "com.example.app",
    "data_classification": "restricted",
    "key_management": "android_keystore"
  }
}
```

#### **AI/ML Integration Tools**

##### 19. `query_llm` - Language Model Queries
Queries local or remote language models for code assistance.

```json
{
  "name": "query_llm",
  "arguments": {
    "prompt": "Generate a Kotlin data class for User with validation",
    "llm_provider": "local",
    "model": "codellama",
    "privacy_mode": true,
    "max_tokens": 1000,
    "temperature": 0.2
  }
}
```
**Supported Providers:**
- `local`: Ollama, LocalAI
- `openai`: GPT-4, GPT-3.5
- `anthropic`: Claude models
- `custom`: Custom API endpoints

##### 20. `analyze_code_with_ai` - AI Code Analysis
Uses AI to analyze code for various aspects.

```json
{
  "name": "analyze_code_with_ai",
  "arguments": {
    "file_path": "src/main/kotlin/UserManager.kt",
    "analysis_type": "security",
    "use_local_model": true,
    "detailed_report": true
  }
}
```
**Analysis Types:**
- `security`: Security vulnerabilities and best practices
- `performance`: Performance optimization suggestions
- `bugs`: Potential bug detection
- `style`: Code style improvements
- `complexity`: Code complexity analysis
- `maintainability`: Maintainability assessment

##### 21. `generate_code_with_ai` - AI Code Generation
Generates code using AI based on natural language descriptions.

```json
{
  "name": "generate_code_with_ai",
  "arguments": {
    "description": "Login screen with biometric authentication and error handling",
    "code_type": "compose_screen",
    "framework": "compose",
    "compliance_requirements": ["gdpr"],
    "include_tests": true,
    "style_guide": "material3"
  }
}
```

#### **File Management Tools**

##### 22. `manage_project_files` - Advanced File Operations
Performs comprehensive file management operations.

```json
{
  "name": "manage_project_files",
  "arguments": {
    "operation": "backup",
    "include_build_files": false,
    "compression": "zip",
    "encryption": true,
    "backup_location": "/path/to/backup",
    "exclude_patterns": ["*.tmp", "build/", ".gradle/"]
  }
}
```
**Operations:**
- `backup`: Create encrypted backups
- `restore`: Restore from backup
- `sync`: Synchronize with cloud storage
- `encrypt`: Encrypt sensitive files
- `decrypt`: Decrypt files (with proper authorization)
- `organize`: Organize files by type/category

##### 23. `setup_cloud_sync` - Cloud Storage Integration
Configures cloud storage synchronization with encryption.

```json
{
  "name": "setup_cloud_sync",
  "arguments": {
    "cloud_provider": "aws_s3",
    "bucket_name": "my-app-backup",
    "encryption_in_transit": true,
    "encryption_at_rest": true,
    "sync_frequency": "hourly",
    "compliance_mode": "gdpr"
  }
}
```

#### **API Integration Tools**

##### 24. `setup_external_api` - API Configuration
Sets up external API integrations with security and monitoring.

```json
{
  "name": "setup_external_api",
  "arguments": {
    "api_name": "PaymentAPI",
    "base_url": "https://api.payment.com/v1/",
    "auth_type": "oauth2",
    "auth_config": {
      "client_id": "your_client_id",
      "scopes": ["payments", "users"]
    },
    "rate_limiting": {
      "requests_per_minute": 100,
      "burst_limit": 10
    },
    "security_features": ["request_signing", "response_validation"],
    "monitoring": true
  }
}
```

##### 25. `call_external_api` - API Calls
Makes secured API calls with comprehensive monitoring.

```json
{
  "name": "call_external_api",
  "arguments": {
    "api_name": "PaymentAPI",
    "endpoint": "/charges",
    "method": "POST",
    "data": {
      "amount": 1000,
      "currency": "USD",
      "description": "Test payment"
    },
    "headers": {
      "Content-Type": "application/json"
    },
    "timeout": 30,
    "retry_config": {
      "max_retries": 3,
      "backoff_strategy": "exponential"
    }
  }
}
```

#### **Testing Tools**

##### 26. `generate_unit_tests` - Unit Test Generation
Generates comprehensive unit tests for Kotlin classes.

```json
{
  "name": "generate_unit_tests",
  "arguments": {
    "file_path": "src/main/kotlin/UserRepository.kt",
    "test_framework": "junit5",
    "mocking_framework": "mockk",
    "include_edge_cases": true,
    "test_coverage_target": 90
  }
}
```

##### 27. `setup_ui_testing` - UI Test Configuration
Sets up UI testing framework with Espresso or Compose testing.

```json
{
  "name": "setup_ui_testing",
  "arguments": {
    "testing_framework": "compose",
    "include_accessibility_tests": true,
    "include_screenshot_tests": true,
    "test_data_setup": "in_memory_database"
  }
}
```

#### **Git Tools**

##### 28. `gitStatus` - Git Repository Status
Get comprehensive Git repository status including branch, changes, and ahead/behind counts.

```json
{
  "name": "gitStatus",
  "arguments": {}
}
```
**Returns:**
- Current branch name
- List of changed files with status
- Ahead/behind counts relative to remote
- Whether repository has uncommitted changes

##### 29. `gitSmartCommit` - Intelligent Commit Messages
Create conventional commit messages based on code changes analysis.

```json
{
  "name": "gitSmartCommit",
  "arguments": {}
}
```
**Features:**
- Analyzes changed files to determine commit type
- Generates conventional commit message
- Automatically stages changes
- Supports feat, fix, docs, refactor, test types

##### 30. `gitCreateFeatureBranch` - Safe Branch Creation
Create feature branches with validation and naming conventions.

```json
{
  "name": "gitCreateFeatureBranch",
  "arguments": {
    "branchName": "user-authentication"
  }
}
```
**Features:**
- Creates `feature/branch-name` format
- Validates branch name format
- Checks for existing branches
- Switches to new branch automatically

##### 31. `gitMergeWithResolution` - Intelligent Merge
Attempt merge with conflict resolution and advice.

```json
{
  "name": "gitMergeWithResolution",
  "arguments": {
    "targetBranch": "main"
  }
}
```
**Features:**
- Attempts automatic merge
- Provides conflict resolution suggestions
- Returns structured conflict hunks
- Offers merge strategy advice

#### **External API Tools**

##### 32. `apiCallSecure` - Secure API Calls
Make authenticated API calls with monitoring and compliance.

```json
{
  "name": "apiCallSecure",
  "arguments": {
    "apiName": "github",
    "endpoint": "/repos/owner/repo/issues",
    "method": "GET",
    "auth": {
      "type": "bearer",
      "token": "ghp_..."
    }
  }
}
```
**Features:**
- Multiple authentication types (Bearer, API Key, OAuth, Basic)
- Automatic retries with backoff
- Request/response monitoring
- Compliance validation

##### 33. `apiMonitorMetrics` - API Metrics Monitoring
Get real-time API usage metrics and performance data.

```json
{
  "name": "apiMonitorMetrics",
  "arguments": {
    "apiName": "github",
    "windowMinutes": 60
  }
}
```
**Returns:**
- Request count and success rate
- Average latency
- Error counts
- Windowed metrics (1m to 7d)

##### 34. `apiValidateCompliance` - API Compliance Validation
Validate API usage against GDPR/HIPAA compliance rules.

```json
{
  "name": "apiValidateCompliance",
  "arguments": {
    "apiName": "payment-api",
    "complianceType": "gdpr"
  }
}
```
**Validates:**
- Data handling practices
- Privacy policy compliance
- Audit logging requirements
- Provides actionable remediation steps

#### **Quality of Life Development Tools**

##### 35. `projectSearch` - Fast Project Search
Perform fast grep searches across project files with context.

```json
{
  "name": "projectSearch",
  "arguments": {
    "query": "TODO|FIXME",
    "includePattern": "*.kt",
    "maxResults": 50,
    "contextLines": 2
  }
}
```
**Features:**
- Uses ripgrep for speed
- Context lines around matches
- Regex pattern support
- File type