企业Kotlin安卓MCP服务器
一个全面的模型上下文协议(MCP)服务器,为AI代理提供对基于Kotlin的Android开发项目的企业级访问。该服务器通过高级安全性、隐私合规性、人工智能集成和全面的开发工具提供上下文感知帮助。
______________________________________________________________________
📋 修订历史
版本2.1 *(目前-2025年8月)*
增强版本:统一智能服务器
🎯 最新改进
- 🧠 智能工具管理:所有27个工具现在都使用具有类似LSP功能的智能代理系统
- 🔄 服务器整合:统一为单一
kotlin_mcp_server.py具有增强的架构 - 📁 清洁建筑:存档的冗余服务器版本,以实现更清晰的项目结构
- ⚡ 增强工具曝光:通过智能管理系统正确暴露的完整工具包
- 🛠️ 改进的刀具路径:本地实现和智能代理之间的智能委托
🔧 架构更改
- 统一服务器:单人
kotlin_mcp_server.py替换多个服务器版本 - 智能代理系统:未完全实现的工具使用具有AI增强功能的智能代理
- 清理文件结构:已存档的旧服务器
archive/legacy-servers/ - 增强型工具管理器:与集成
IntelligentMCPToolManager高级功能 - 完整的工具覆盖范围:所有32个工具均正确暴露且功能正常
📊 工具实施状态
- 全面实施:6个工具(format_code、run_lint、generate-docs、create_copose_component、setup_mvvmarchitecture、security_harding)
- 遗留集成:3个核心工具(create_kotlin_file、gradle_build、analyze_project)
- 智能代理:23个具有智能回退实现的工具
- 总量可用:32个工具,全面覆盖Android开发
版本2.0 *(2025年8月)*
主要版本:AI增强模块化架构
🎯 关键改进
- 🤖 AI集成:从模板生成器转换为AI驱动的开发助手
- 🏗️ 模块化架构:将整体结构重构为6个专业模块
- 🌍 动态配置:消除了跨平台可移植性的所有硬编码路径
- ⚡ 增强工具:通过人工智能增强的实施,从30个工具扩展到31个工具
- 🛡️ 安全强化:添加了可配置的审计跟踪和合规性监控
- 📦 零配置设置:具有自动环境检测功能的智能安装程序
🔧 技术变更
- 模块化设计:拆分为
ai/,android/,gradle/,security/,testing/,utils/模块 - AI驱动的代码生成:利用LLM调用生产就绪代码(无TODO)
- 环境变量支持:所有配置现在都使用动态环境变量
- 跨平台路径:通用
~符号替换了特定于操作系统的硬编码路径 - 增强的错误处理:全面的验证和优雅的故障恢复
- 性能优化:通过更好的资源管理简化工具执行
📊 移民影响
- 工具: 30 → 32 工具(107%功能对等+增强)
- 文件大小:优化的模块化结构与整体式方法
- 配置:无需手动路径配置
- 兼容性:保持与现有设置的完全向后兼容性
版本1.0 *(遗产-2025年8月之前)*
初始版本:基于模板的代码生成器
- ✅ 配备30个工具的基本MCP服务器
- ✅ 基于模板的Kotlin/Android代码生成
- ✅ 使用硬编码路径进行手动配置
- ✅ 一体化架构
- ✅ 基本安全和合规功能
______________________________________________________________________
🌟 企业功能概述
🔒 安全与隐私合规
- GDPR合规 -完整实施,包括同意管理、数据可移植性、删除权
- HIPAA合规性 -具有审计日志记录、访问控制和加密的医疗保健级安全
- 数据加密 -使用PBKDF2密钥推导对敏感数据进行AES-256加密
- 审计跟踪 -具有合规标志和安全事件跟踪的全面日志记录
- 隐私设计 -为所有操作提供内置隐私保护
🤖 AI/ML集成
- 本地LLM支持 -Ollama、LocalAI和自托管变压器
- 外部LLM API -OpenAI GPT-4,人类克劳德,自定义端点
- AI驱动的代码分析 -安全性、性能和复杂性分析
- 智能代码生成 -上下文感知Kotlin/Android代码创建
- ML模型集成 -TensorFlow Lite、ONNX、适用于Android应用程序的PyTorch Mobile
📁 高级文件管理
- 企业文件操作 -使用审计跟踪进行备份、还原、同步、加密、解密
- 实时同步 -具有自动同步功能的文件系统监视器
- 云存储集成 -AWS S3、Google Cloud、Azure,具有端到端加密功能
- 智能文件分类 -自动敏感数据检测和加密
- 版本控制 -具有冲突解决功能的Git感知操作
🌐 外部API集成
- 全面的身份验证支持 -API密钥,OAuth 2.0,JWT,基本验证
- 安全功能 -速率限制、请求日志记录、响应验证
- 实时监控 -API使用指标、性能跟踪、成本分析
- 合规性验证 -符合GDPR/HHIPAA的API处理
🏗️ 高级Android开发
- 体系结构模式 -MVVM、清洁架构、依赖注入
- 现代UI开发 -Jetpack Compose、自定义视图、复杂布局
- 数据库集成 -带加密、迁移处理的房间
- 网络层 -改装、GraphQL、WebSocket支持
- 测试框架 -全面的测试生成和执行
______________________________________________________________________
🚀 快速启动和安装
✨ 升级到V2.0亮点
🤖 AI增强开发:现在利用您的AI助手生成生产就绪代码,而不是基本模板!
之前(V1.0):
- ❌ 基于模板的代码,带有TODO占位符
- ❌ 配置文件中的手动路径编辑
- ❌ 单片架构(单个大文件)
- ❌ 硬编码路径和用户特定配置
- ❌ 30种基本工具,人工智能集成有限
在(V2.0)之后:
- ✅ AI驱动的代码生成:完整的、上下文感知的实现
- ✅ 零配置设置:
python3 install.py处理一切 - ✅ 模块化架构:清洁、可维护的6模块结构
- ✅ 动态配置:具有环境变量的跨平台
- ✅ 31增强工具:AI与智能错误处理集成
📋 系统要求
- Python 3.8+ (3.9+推荐)
- 点 (Python包管理器)
- Git (用于克隆存储库)
- 支持MCP的IDE (VS Code、JetBrains IDE、Claude Desktop)
🔧 安装步骤
1.克隆存储库
git clone
cd kotlin-mcp-server2.自动安装和配置
该项目包括一个增强的安装脚本,可以自动处理所有配置:
# 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安装类型:
1- 便携的:直接从项目目录运行2- 系统:将命令安装到PATH(kotlin-android-mcp)3- 模块:启用python -m kotlin_mcp_server
配置示例:
# 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安装程序的作用:
- ✅ 安装所有Python依赖项 从
requirements.txt - ✅ 创建特定于平台的配置文件 (克劳德,VS代码,通用)
- ✅ 设置适当的文件权限 用于脚本
- ✅ 配置环境变量 根据您的选择
- ✅ 消除了手动路径更新 在配置文件中
- ✅ 提供清晰的集成说明 对于您的设置
3.手动安装(替代)
如果您更喜欢手动安装:
# 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')"已安装的关键依赖项:
- 核心MCP:
python-dotenv,pydantic - 安全:
cryptography,bcrypt,PyJWT - 数据库:
aiosqlite,sqlalchemy - HTTP客户端:
aiohttp,httpx - 文件管理:
aiofiles,watchdog - 测试:
pytest,pytest-asyncio,coverage - 代码质量:
black,flake8,pylint,mypy - 安全工具:
bandit,safety
4.V2.0架构和工具增强
🏗️ 模块化架构设计
V2.0版本引入了一个干净、可维护的模块化结构:
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增强工具功能
| 工具类别 | V1.0(模板) | V2.0(AI增强) |
|---|---|---|
| 代码生成 | TODO的基本模板 | 生产就绪、上下文感知的实现 |
| 体系结构模式 | 骨架代码 | 完整的MVVM,干净的架构模式 |
| UI组件 | 静态布局 | 动态Jetpack与业务逻辑组合 |
| 数据库操作 | 架构模板 | 带迁移的全室实施 |
| 测试 | 测试存根 | 具有边缘情况的综合测试套件 |
| 安全 | 基本验证 | 符合法规的企业级安全 |
⚡ 性能和可靠性改进
- 31工具 (与V1.0中的30相比),具有增强的AI集成
- 错误恢复:巧妙处理人工智能服务中断
- 情境感知:工具了解项目结构和要求
- 资源优化:高效的内存使用和更快的执行
- 与跨平台支持:通用配置系统
5.IDE集成设置
安装后,脚本会生成即用型配置文件:
mcp_config_claude.json-适用于克劳德桌面mcp_config_vscode.json-用于VS代码和光标mcp_config.json-对于其他MCP客户端
集成说明:
🔹 克劳德桌面:从以下位置复制内容 mcp_config_claude.json 致:
- 苹果电脑:
~/Library/Application Support/Claude/claude_desktop_config.json - 视窗:
%APPDATA%\Claude\claude_desktop_config.json - Linux:
~/.config/claude/claude_desktop_config.json
🔹 VS代码/光标:添加到您的VS代码 settings.json:
{
"mcp.server.configFiles": [
"/absolute/path/to/mcp_config_vscode.json"
]
}🔹 其他IDE:使用 mcp_config.json 与您的MCP客户端
5.环境配置(高级)
对于需要自定义环境设置的高级用户: 创建一个 .env 项目根目录中的文件(仅高级配置需要):
# Copy the example file and customize
cp .env.example .env
# Edit with your settings
nano .env # or your preferred editor可选变量:
# 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💡 备注:安装脚本会自动配置项目路径和服务器设置,因此只需要对AI集成或自定义安全设置等高级功能进行手动环境配置。
6.安装所需的IDE扩展/插件
请参阅 插件要求 下面的部分介绍IDE特定的扩展。
7.测试安装
# 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⚡ 快速设置命令
# 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🎯 安装摘要
增强的安装过程 消除了手动配置的需要:
✅ 之前(手动):用户必须手动编辑配置文件、查找路径、更新环境变量\ ✅ 之后(自动):一个命令创建所有可用的内容
主要改进:
- 🚀 零手动配置:不再进行路径更新或变量编辑
- 🎛️ 交互式和非交互式:适用于所有用户的两种模式
- 🔧 平台特定配置:为每个IDE/客户端生成优化文件
- 📋 清除指令:为您的设置提供精确的集成步骤
- ✨ 智能默认值:智能地处理环境变量
🐳 Docker部署(可选)
对于容器化部署,该项目包括全面的Docker支持:
快速Docker设置
# 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-serverDocker功能
- 🔒 安全:非root用户,攻击面最小
- 📦 优化:多阶段构建,分层缓存
- 🔍 健康检查:自动集装箱健康监测
- 🛠️ 发展:用于实时开发的音量挂载
- 🚀 生产:用于生产部署的守护进程模式
可用命令
./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有关Docker设置的详细说明,请参阅
______________________________________________________________________
🎯 证明它:生成真正的Android应用程序
准备好看到系统生成完整的、可投入生产的Android应用程序了吗? 按照以下步骤见证完整的E2E工作流程:
🚀 快速入门:生成您的第一个应用程序
# 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您将获得:
- ✅ 完成Gradle项目 (Kotlin、作曲、Hilt、MVVM)
- ✅ 运行中的Android应用程序 带主屏幕+详细信息屏幕
- ✅ 房间数据库 与实体和DAO
- ✅ 改造网络层 使用API服务
- ✅ 单元测试 通过(Roboelectric+JVM测试)
- ✅ APK已准备好安装 在设备/模拟器上
🔧 可用命令
# 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📊 生成的应用程序功能
生成的 e2e/sampleapp 包括:
🏗️ 架构:
- 带有ViewModel的MVVM模式
- Hilt依赖注入
- 清洁建筑原则
🎨 UI/UX:
- Jetpack合成屏幕
- 材料3设计
- 屏幕间导航
💾 数据层:
- 包含实体的房间数据库
- 仓库模式
- 迁移骨架
🌐 网络:
- 改造API客户
- OkHttp拦截器
- 错误处理
🧪 测试:
- ViewModel的单元测试
- 使用Roboelectric进行DAO测试
- API服务测试
📱 构建:
- 调试APK生成
- 棉绒/格式检查
- Gradle构建优化
⚙️ 环境变量
# 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🔍 故障排除
Gradle构建失败:
# 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侧车连接问题:
# 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.jarAPK未生成:
# Check build logs
cd e2e/sampleapp && ./gradlew assembleDebug --info
# Ensure JDK 17 is used
java -version # Should show Java 17📈 性能基准
该系统针对以下方面进行了优化:
- 侧车启动:\ Unit"
], "include_preview": true, "material_design": "material3" } }
**组件类型:**
- `composable`:标准可组合功能
- `stateful`:与内部状态可组合
- `stateless`:纯UI可组合
- `layout`:布局可与儿童组合
##### 10. `create_custom_view` -自定义Android视图
创建具有适当生命周期管理的自定义视图类。
{ "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"} ] } }
#### **架构和模式工具**
##### 11. `setup_mvvm_architecture` -MVVM实施
使用ViewModel、Repository和UI层设置完整的MVVM架构。
{ "name": "setup_mvvm_architecture", "arguments": { "feature_name": "UserProfile", "package_name": "com.example.userprofile", "include_repository": true, "include_use_cases": true, "state_management": "compose" } }
**生成的文件:**
- 带状态管理的ViewModel
- 具有数据源抽象的存储库
- 业务逻辑用例
- UI可组合或片段
- 国家级和封闭式活动课程
##### 12. `setup_dependency_injection` -DI框架设置
使用Hilt或Dagger配置依赖注入。
{ "name": "setup_dependency_injection", "arguments": { "di_framework": "hilt", "modules": ["DatabaseModule", "NetworkModule", "RepositoryModule"], "application_class": "MyApplication" } }
##### 13. `setup_room_database` -数据库设置
使用实体、DAO和迁移创建Room数据库实现。
{ "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` -网络层
设置具有正确错误处理和拦截器的改装API接口。
{ "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 } }
#### **安全与合规工具**
##### 15. `encrypt_sensitive_data` -数据加密
使用行业标准加密对敏感数据进行加密。
{ "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实施
实施完整的GDPR合规框架。
{ "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 } }
**生成的组件:**
- 同意管理UI和逻辑
- 数据导出功能
- 用户数据删除工作流
- 隐私政策模板
- 审计记录系统
##### 17. `implement_hipaa_compliance` -HIPAA实施
实施符合HIPAA标准的安全措施。
{ "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` -安全数据存储
为敏感数据配置加密存储。
{ "name": "setup_secure_storage", "arguments": { "storage_type": "room_encrypted", "package_name": "com.example.app", "data_classification": "restricted", "key_management": "android_keystore" } }
#### **AI/ML集成工具**
##### 19. `query_llm` -语言模型查询
查询本地或远程语言模型以获取代码帮助。
{ "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 } }
**支持的提供商:**
- `local`:Ollama,LocalAI
- `openai`:GPT-4、GPT-3.5
- `anthropic`:克劳德模型
- `custom`:自定义API终结点
##### 20. `analyze_code_with_ai` -AI代码分析
使用AI分析代码的各个方面。
{ "name": "analyze_code_with_ai", "arguments": { "file_path": "src/main/kotlin/UserManager.kt", "analysis_type": "security", "use_local_model": true, "detailed_report": true } }
**分析类型:**
- `security`:安全漏洞和最佳做法
- `performance`:性能优化建议
- `bugs`:潜在错误检测
- `style`:代码样式改进
- `complexity`:代码复杂性分析
- `maintainability`:可维护性评估
##### 21. `generate_code_with_ai` -AI代码生成
使用基于自然语言描述的AI生成代码。
{ "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" } }
#### **文件管理工具**
##### 22. `manage_project_files` -高级文件操作
执行全面的文件管理操作。
{ "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/"] } }
**操作:**
- `backup`:创建加密备份
- `restore`:从备份还原
- `sync`:与云存储同步
- `encrypt`:加密敏感文件
- `decrypt`:解密文件(经过适当授权)
- `organize`:按类型/类别组织文件
##### 23. `setup_cloud_sync` -云存储集成
使用加密配置云存储同步。
{ "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集成工具**
##### 24. `setup_external_api` -API配置
设置外部API与安全和监控的集成。
{ "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调用
通过全面监控进行安全的API调用。
{ "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" } } }
#### **测试工具**
##### 26. `generate_unit_tests` -单元测试生成
为Kotlin类生成全面的单元测试。
{ "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测试配置
使用Espresso或Compose测试设置UI测试框架。
{ "name": "setup_ui_testing", "arguments": { "testing_framework": "compose", "include_accessibility_tests": true, "include_screenshot_tests": true, "test_data_setup": "in_memory_database" } }
#### **Git工具**
##### 28. `gitStatus` -Git存储库状态
获取全面的Git存储库状态,包括分支、更改和超前/滞后计数。
{ "name": "gitStatus", "arguments": {} }
**退货:**
- 当前分支机构名称
- 已更改文件及其状态列表
- 相对于远程的领先/落后计数
- 存储库是否有未提交的更改
##### 29. `gitSmartCommit` -智能提交消息
基于代码更改分析创建常规提交消息。
{ "name": "gitSmartCommit", "arguments": {} }
**特征:**
- 分析更改的文件以确定提交类型
- 生成常规提交消息
- 自动分期更改
- 支持feat、fix、docs、重构、测试类型
##### 30. `gitCreateFeatureBranch` -安全分支创建
使用验证和命名约定创建要素分支。
{ "name": "gitCreateFeatureBranch", "arguments": { "branchName": "user-authentication" } }
**特征:**
- 创建 `feature/branch-name` 格式
- 验证分支名称格式
- 检查现有分支机构
- 自动切换到新分支
##### 31. `gitMergeWithResolution` -智能合并
尝试与冲突解决和建议相结合。
{ "name": "gitMergeWithResolution", "arguments": { "targetBranch": "main" } }
**特征:**
- 尝试自动合并
- 提供冲突解决建议
- 返回结构化冲突块
- 提供合并策略建议
#### **外部API工具**
##### 32. `apiCallSecure` -安全的API调用
在监控和遵守的情况下进行经过身份验证的API调用。
{ "name": "apiCallSecure", "arguments": { "apiName": "github", "endpoint": "/repos/owner/repo/issues", "method": "GET", "auth": { "type": "bearer", "token": "ghp_..." } } }
**特征:**
- 多种身份验证类型(承载、API密钥、OAuth、基本)
- 具有回退功能的自动重试
- 请求/响应监控
- 合规性验证
##### 33. `apiMonitorMetrics` -API指标监测
获取实时API使用指标和性能数据。
{ "name": "apiMonitorMetrics", "arguments": { "apiName": "github", "windowMinutes": 60 } }
**退货:**
- 请求计数和成功率
- 平均延迟
- 错误计数
- 窗口化指标(1m至7d)
##### 34. `apiValidateCompliance` -API合规性验证
根据GDPR/HIPAA合规性规则验证API的使用情况。
{ "name": "apiValidateCompliance", "arguments": { "apiName": "payment-api", "complianceType": "gdpr" } }
**验证:**
- 数据处理实践
- 隐私政策合规性
- 审计日志记录要求
- 提供可操作的补救步骤
#### **生活质量发展工具**
##### 35. `projectSearch` -快速项目搜索
在具有上下文的项目文件中执行快速grep搜索。
{ "name": "projectSearch", "arguments": { "query": "TODO|FIXME", "includePattern": "*.kt", "maxResults": 50, "contextLines": 2 } }
**特征:**
- 使用ripgrep提高速度
- 比赛周围的背景线
- 正则表达式模式支持
- 文件类型筛选
##### 36. `todoListFromCode` -TODO/FIXME提取
从代码库中解析和组织TODO/FIXME注释。
{ "name": "todoListFromCode", "arguments": { "includePattern": "*.{kt,java,py,js,ts}", "maxResults": 100 } }
**退货:**
- 按优先级组织(FIXME>TODO>XXX>HACK)
- 文件位置和行号
- 完整评论上下文
- 汇总统计
##### 37. `readmeGenerateOrUpdate` -README管理
生成或更新带有徽章、设置说明和工具目录的README。
{ "name": "readmeGenerateOrUpdate", "arguments": { "forceRegenerate": false } }
**生成:**
- 建立身份徽章
- 设置和使用说明
- 完整的工具目录
- 环境变量文档
##### 38. `changelogSummarize` -变更日志处理
将常规提交汇总到分组的发布说明中。
{ "name": "changelogSummarize", "arguments": { "changelogPath": "CHANGELOG.md", "version": "latest" } }
**按类型提交的组:**
- 特性
- 错误修正
- 文档
- 突破性变化
##### 39. `buildAndTest` -建造和测试管道
运行Gradle/Maven构建并返回详细的测试结果。
{ "name": "buildAndTest", "arguments": { "buildTool": "auto", "skipTests": false } }
**退货:**
- 构建成功/失败
- 未通过测试的详细信息
- 构建工件
- 性能指标
##### 40. `dependencyAudit` -依赖性安全审计
审核Gradle依赖关系的漏洞和许可证合规性。
{ "name": "dependencyAudit", "arguments": {} }
**检查:**
- OSV漏洞数据库
- 许可证兼容性
- 过时的依赖关系
- 安全公告
##### 41. `securityHardening` -安全强化管理
管理安全强化功能,包括RBAC、速率限制、缓存和监控。
{ "name": "securityHardening", "arguments": { "operation": "get_metrics" } }
**操作:**
- `get_metrics` -获取安全指标和监控数据
- `assign_role` -分配用户角色(管理员、开发人员、只读、访客)
- `check_permission` -检查用户操作权限
- `clear_cache` -清除安全缓存
- `export_telemetry` -导出遥测数据
**特征:**
- 基于角色的访问控制(RBAC)
- 滑动窗口速率限制
- 断路器型式
- 基于TTL的缓存
- 全面的指标收集
- 遥测输出功能
### 🚀 **快速入门工具示例**
#### **完成项目设置工作流**
以下是一个逐步建立具有企业功能的新Android项目的工作流程:
1. Analyze existing project structure
{ "name": "analyze_project", "arguments": { "analysis_type": "architecture", "include_dependencies": true } }
2. Set up MVVM architecture
{ "name": "setup_mvvm_architecture", "arguments": { "feature_name": "UserManagement", "package_name": "com.example.users", "include_repository": true, "state_management": "compose" } }
3. Configure dependency injection
{ "name": "setup_dependency_injection", "arguments": { "di_framework": "hilt", "modules": ["DatabaseModule", "NetworkModule"] } }
4. Set up secure database
{ "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"} ] } ], "enable_encryption": true } }
5. Implement compliance (if required)
{ "name": "implement_gdpr_compliance", "arguments": { "package_name": "com.example.app", "features": ["consent_management", "data_portability"], "include_ui": true } }
6. Generate UI components
{ "name": "create_compose_component", "arguments": { "component_name": "UserListScreen", "component_type": "stateful", "include_preview": true, "material_design": "material3" } }
7. Set up API integration
{ "name": "setup_retrofit_api", "arguments": { "base_url": "https://api.example.com/", "endpoints": [ { "name": "getUsers", "method": "GET", "path": "users", "response_type": "List" } ], "include_interceptors": ["logging", "auth"] } }
8. Generate comprehensive tests
{ "name": "generate_unit_tests", "arguments": { "file_path": "src/main/kotlin/UserRepository.kt", "test_framework": "junit5", "include_edge_cases": true } }
9. Build and test
{ "name": "gradle_build", "arguments": { "task": "assembleDebug", "clean_build": true } }
{ "name": "run_tests", "arguments": { "test_type": "all", "generate_report": true } }
#### **AI驱动的开发示例**
Generate a complete login feature using AI
{ "name": "generate_code_with_ai", "arguments": { "description": "Complete login feature with email/password, biometric authentication, remember me option, forgot password flow, and proper error handling", "code_type": "feature", "framework": "compose", "compliance_requirements": ["gdpr"], "include_tests": true } }
Analyze existing code for security issues
{ "name": "analyze_code_with_ai", "arguments": { "file_path": "src/main/kotlin/AuthManager.kt", "analysis_type": "security", "detailed_report": true } }
Get AI assistance for complex implementation
{ "name": "query_llm", "arguments": { "prompt": "How do I implement secure biometric authentication in Android with fallback to PIN? Include error handling for different biometric states.", "llm_provider": "local", "privacy_mode": true } }
### 🛠️ **工具使用最佳实践**
#### **文件路径约定**
始终使用项目根目录的相对路径:
✅ Correct
"file_path": "src/main/kotlin/com/example/User.kt"
❌ Incorrect
"file_path": "/absolute/path/to/User.kt"
#### **包命名**
遵循Android软件包命名约定:
✅ Correct
"package_name": "com.company.app.feature.user"
❌ Incorrect
"package_name": "User.Package"
#### **安全最佳实践**
- 始终对敏感数据使用加密
- 从一开始就实施适当的合规功能
- 对API密钥和机密使用安全存储
- 启用审核日志记录以满足合规要求
#### **性能优化**
- 使用 `parallel: true` 尽可能为Gradle构建
- 逐步生成测试,而不是一次生成所有测试
- 使用本地LLM提供程序进行隐私敏感代码分析
- 为API设置启用缓存
#### **错误处理**
所有工具都提供全面的错误信息:
{ "success": false, "error": "File already exists", "details": { "file_path": "src/main/kotlin/User.kt", "suggestion": "Use a different file name or set overwrite: true" } }
### 📊 **工具响应格式**
#### **成功响应**
{ "success": true, "result": { "files_created": ["User.kt", "UserTest.kt"], "lines_of_code": 125, "compilation_status": "success" }, "metadata": { "execution_time": "2.3s", "tools_used": ["kotlin_compiler", "test_generator"] } }
#### **错误响应**
{ "success": false, "error": "Compilation failed", "details": { "error_type": "compilation_error", "line_number": 23, "message": "Unresolved reference: undefinedVariable", "suggestions": [ "Check variable declaration", "Verify imports" ] } }
### �🔒 **安全和隐私功能**
#### GDPR合规实施
{ "name": "implement_gdpr_compliance", "arguments": { "package_name": "com.example.app", "features": [ "consent_management", "data_portability", "right_to_erasure", "privacy_policy" ] } }
**生成的功能:**
- 同意管理UI组件
- 数据导出功能
- 用户数据删除工作流
- 隐私政策模板
- 法律依据跟踪
#### HIPAA合规性实施
{ "name": "implement_hipaa_compliance", "arguments": { "package_name": "com.healthcare.app", "features": [ "audit_logging", "access_controls", "encryption", "secure_messaging" ] } }
**生成的功能:**
- 全面的审计记录系统
- 基于角色的访问控制框架
- PHI加密工具
- 安全的消息传递基础架构
- 风险评估工具
#### 数据加密
{ "name": "encrypt_sensitive_data", "arguments": { "data": "Patient: John Doe, SSN: 123-45-6789", "data_type": "phi", "compliance_level": "hipaa" } }
#### 安全存储设置
{ "name": "setup_secure_storage", "arguments": { "storage_type": "room_encrypted", "package_name": "com.example.app", "data_classification": "restricted" } }
### 🤖 **AI集成功能**
#### 本地LLM查询
{ "name": "query_llm", "arguments": { "prompt": "Generate a Kotlin data class for User with validation", "llm_provider": "local", "privacy_mode": true, "max_tokens": 1000 } }
#### AI驱动的代码分析
{ "name": "analyze_code_with_ai", "arguments": { "file_path": "src/main/UserManager.kt", "analysis_type": "security", "use_local_model": true } }
**分析类型:**
- `security` -漏洞和安全最佳实践
- `performance` -性能优化建议
- `bugs` -潜在错误检测
- `style` -代码风格和格式改进
- `complexity` -代码复杂性分析
#### AI代码生成
{ "name": "generate_code_with_ai", "arguments": { "description": "Login screen with biometric authentication", "code_type": "component", "framework": "compose", "compliance_requirements": ["gdpr", "hipaa"] } }
**代码类型:**
- `class` -带方法的Kotlin类
- `function` -独立功能
- `layout` -XML布局文件
- `test` -单元和集成测试
- `component` -Jetpack组合组件
### 📁 **文件管理操作**
#### 高级备份
{ "name": "manage_project_files", "arguments": { "operation": "backup", "target_path": "./src", "destination": "./backups", "encryption_level": "high" } }
#### 实时同步
{ "name": "manage_project_files", "arguments": { "operation": "sync", "target_path": "./src", "destination": "./remote-sync", "sync_strategy": "real_time" } }
#### 云存储同步
{ "name": "setup_cloud_sync", "arguments": { "cloud_provider": "aws", "sync_strategy": "scheduled", "encryption_in_transit": true, "compliance_mode": "gdpr" } }
**支持的操作:**
- `backup` -使用清单创建加密备份
- `restore` -通过完整性检查从备份还原
- `sync` -双向同步与冲突解决
- `encrypt` -就地加密敏感文件
- `decrypt` -使用适当的授权解密文件
- `archive` -创建压缩档案
- `extract` -通过验证提取档案
- `search` -基于内容的文件发现
- `analyze` -文件结构和使用分析
### 🌐 **外部API集成**
#### API集成设置
{ "name": "integrate_external_api", "arguments": { "api_name": "HealthRecordsAPI", "base_url": "https://api.healthrecords.com", "auth_type": "oauth", "security_features": [ "rate_limiting", "request_logging", "response_validation" ], "compliance_requirements": ["hipaa"] } }
#### API使用监控
{ "name": "monitor_api_usage", "arguments": { "api_name": "HealthRecordsAPI", "metrics": [ "latency", "error_rate", "usage_volume", "cost" ], "alert_thresholds": { "error_rate": 5.0, "latency_ms": 2000 } } }
**身份验证类型:**
- `none` -无需身份验证
- `api_key` -标头或查询中的API键
- `oauth` -OAuth 2.0流程
- `jwt` -JSON Web令牌
- `basic` -基本HTTP身份验证
### 🏗️ **高级Android开发**
#### MVVM架构设置
{ "name": "setup_mvvm_architecture", "arguments": { "feature_name": "UserProfile", "package_name": "com.example.app", "include_repository": true, "include_use_cases": true, "data_source": "both" } }
#### Jetpack组合组件
{ "name": "create_compose_component", "arguments": { "file_path": "ui/components/LoginForm.kt", "component_name": "LoginForm", "component_type": "component", "package_name": "com.example.ui", "uses_state": true, "uses_navigation": false } }
#### 房间数据库设置
{ "name": "setup_room_database", "arguments": { "database_name": "AppDatabase", "package_name": "com.example.data", "entities": ["User", "Profile", "Settings"], "include_migration": true } }
#### 改造API客户
{ "name": "setup_retrofit_api", "arguments": { "api_name": "UserApiService", "package_name": "com.example.network", "base_url": "https://api.example.com", "endpoints": [ { "method": "GET", "path": "/users/{id}", "name": "getUser" } ], "include_interceptors": true } }
#### 依赖注入(Hilt)
{ "name": "setup_dependency_injection", "arguments": { "module_name": "NetworkModule", "package_name": "com.example.di", "injection_type": "network" } }
#### ML模型集成
{ "name": "integrate_ml_model", "arguments": { "model_type": "tflite", "model_path": "assets/model.tflite", "use_case": "image_classification", "privacy_preserving": true } }
### 🛠️ **工具特定故障排除**
#### **Gradle构建问题**
Tool: gradle_build
Common solutions:
1. Clear Gradle cache
{ "name": "gradle_build", "arguments": { "task": "clean", "clean_build": true } }
2. Check Java version
echo $JAVA_HOME java -version
3. Fix permission issues (macOS/Linux)
chmod +x gradlew
4. Enable verbose output for debugging
{ "name": "gradle_build", "arguments": { "task": "assembleDebug", "gradle_args": ["--debug", "--stacktrace"] } }
#### **AI集成问题**
Tool: query_llm, analyze_code_with_ai, generate_code_with_ai
Local LLM not responding
curl http://localhost:11434/api/generate -d '{"model":"codellama","prompt":"test"}'
API key issues
python3 -c "import os; print('OpenAI:', bool(os.getenv('OPENAI_API_KEY')))"
Privacy mode for sensitive code
{ "name": "query_llm", "arguments": { "prompt": "Your prompt here", "llm_provider": "local", # Force local processing "privacy_mode": true # No external API calls } }
#### **文件创建问题**
Tool: create_kotlin_file, create_layout_file, create_compose_component
Permission denied
sudo chown -R $(whoami):$(whoami) src/
File already exists
{ "name": "create_kotlin_file", "arguments": { "file_path": "src/main/kotlin/User.kt", "overwrite": true # Force overwrite } }
Invalid package structure
Ensure your file path matches package structure:
File: src/main/kotlin/com/example/User.kt
Package: com.example
#### **安全工具问题**
Tool: encrypt_sensitive_data, implement_gdpr_compliance
Cryptography not available
pip install cryptography>=41.0.0
Test encryption
python3 -c "from cryptography.fernet import Fernet; print('✅ Encryption available')"
GDPR compliance setup
{ "name": "implement_gdpr_compliance", "arguments": { "package_name": "com.example.app", "features": ["consent_management"], # Start with basic features "dry_run": true # Test mode first } }
#### **数据库设置问题**
Tool: setup_room_database, setup_secure_storage
Check Android Room version compatibility
grep "room_version" build.gradle
Test database creation
{ "name": "setup_room_database", "arguments": { "database_name": "TestDB", "entities": [{"name": "TestEntity", "fields": [{"name": "id", "type": "String", "primaryKey": true}]}], "validate_only": true # Check schema without creating files } }
#### **网络/API问题**
Tool: setup_retrofit_api, call_external_api
Test network connectivity
curl -I https://api.example.com/
Verify SSL certificates
openssl s_client -connect api.example.com:443
Debug API calls
{ "name": "call_external_api", "arguments": { "api_name": "TestAPI", "endpoint": "/health", "method": "GET", "debug_mode": true, # Enable detailed logging "timeout": 10 # Shorter timeout for testing } }
### 🧪 **测试和质量保证**
#### 综合测试生成
{ "name": "generate_test_suite", "arguments": { "class_to_test": "UserRepository", "test_type": "unit", "include_mockito": true, "test_coverage": "comprehensive" } }
**测试类型:**
- `unit` -带模拟的单元测试
- `integration` -具有真实依赖关系的集成测试
- `ui` -使用Espresso进行UI测试
______________________________________________________________________
## 🏥 **行业特定示例**
### 医疗保健应用
1. Implement HIPAA compliance
{ "name": "implement_hipaa_compliance", "arguments": { "package_name": "com.health.tracker", "features": ["audit_logging", "encryption", "access_controls"] } }
2. Setup secure storage for PHI
{ "name": "setup_secure_storage", "arguments": { "storage_type": "room_encrypted", "data_classification": "restricted" } }
3. Generate patient form with AI
{ "name": "generate_code_with_ai", "arguments": { "description": "Patient intake form with validation", "compliance_requirements": ["hipaa"] } }
### 金融应用
1. Implement GDPR compliance
{ "name": "implement_gdpr_compliance", "arguments": { "features": ["consent_management", "data_portability"] } }
2. Setup secure API integration
{ "name": "integrate_external_api", "arguments": { "api_name": "PaymentAPI", "auth_type": "oauth", "security_features": ["rate_limiting", "request_logging"] } }
3. Enable cloud backup with encryption
{ "name": "setup_cloud_sync", "arguments": { "cloud_provider": "aws", "encryption_in_transit": true, "compliance_mode": "gdpr" } }
______________________________________________________________________
## 🔧 **配置和部署**
### Docker部署
Build and run with Docker
docker-compose up -d
Or build manually
docker build -t kotlin-mcp-server . docker run -p 8000:8000 -v $(pwd):/workspace kotlin-mcp-server
### AI代理集成
#### 克劳德桌面
增添 `~/Library/Application Support/Claude/claude_desktop_config.json`:
{ "mcpServers": { "kotlin-android": { "command": "python", "args": ["/path/to/kotlin-mcp-server/kotlin_mcp_server.py"], "env": { "WORKSPACE_PATH": "/path/to/your/android/project" } } } }
#### VS代码扩展
使用以下配置 `mcp_config_vscode.json`
______________________________________________________________________
## ⚙️ **配置和插件要求**
本节提供了有关为不同IDE和所需插件配置MCP服务器的详细说明。
### 🔌 **所需插件/扩展**
#### **VS代码扩展**
Install required VS Code extensions
code --install-extension ms-python.python code --install-extension ms-python.pylint code --install-extension ms-python.black-formatter code --install-extension ms-python.isort code --install-extension ms-python.mypy-type-checker code --install-extension ms-toolsai.jupyter
**通过VS Code Marketplace手动安装:**
- **python** (ms-python.python)-核心python支持
- **皮林** (ms-python.pylint)-代码linting
- **黑色格式化程序** (ms-python.black格式化程序)-代码格式化
- **isort** (ms-python.iort)-导入排序
- **朱庇特** (ms-toolsai.jupyter)-笔记本电脑支持(可选)
- **VS代码的MCP** -模型上下文协议支持(如果可用)
#### **JetBrains集成开发环境(IntelliJ IDEA、安卓工作室)**
**所需插件:**
- **Python插件** -用于Python脚本执行
- **MCP插件** -模型上下文协议支持(查看JetBrains市场)
- **Kotlin插件** -为Android Studio内置,为IntelliJ安装
- **安卓插件** -内置于Android Studio
#### **Claude桌面集成**
不需要额外的插件-使用内置的MCP支持。
### 🛠️ **IDE配置**
#### **Visual Studio Code**
1. **安装Python扩展包:**
code --install-extension ms-python.python
1. **配置MCP服务器:**
安装脚本生成 `mcp_config_vscode.json` 正确的路径。只需添加到VS代码 `settings.json` (`Cmd/Ctrl + Shift + P` → “首选项:打开设置(JSON)”):
{ "mcp.server.configFiles": [ "/absolute/path/to/your/kotlin-mcp-server/mcp_config_vscode.json" ], "python.defaultInterpreterPath": "/usr/bin/python3", "python.linting.enabled": true, "python.formatting.provider": "black", "python.sortImports.path": "isort" }
**💡 专业提示:** 安装脚本提供了您需要使用的确切路径。
1. **工作区设置(.vcode/Settings.json):**
{ "python.pythonPath": "python3", "mcp.server.autoStart": true, "mcp.server.logLevel": "info" }
#### **JetBrains集成开发环境(IntelliJ IDEA、安卓工作室)**
1. **安装所需插件:**
- 首选 `File > Settings > Plugins` (Windows/Linux)或 `IntelliJ IDEA > Preferences > Plugins` (Mac)
- 从市场搜索并安装“MCP”插件
- 安装“Python”插件(如果尚未可用)
1. **配置MCP服务器:**
安装脚本生成 `mcp_config.json` 具有适当的配置。在IDE中:
- 首选 `File > Settings > Tools > MCP Server`
- 点击 `+` 要添加新服务器,请执行以下操作:
- **姓名:** 您的自定义服务器名称(在安装过程中配置)
- **配置文件:** 选择生成的 `mcp_config.json`
- **自动启动:** 启用
1. **Android工作室特定:**
**💡 注:** 替换 `your-server-name` 使用您在安装过程中选择的服务器名称。
#### **克劳德桌面**
1. **配置文件位置:**
- **雨衣:** `~/Library/Application Support/Claude/claude_desktop_config.json`
- **窗户:** `%APPDATA%\Claude\claude_desktop_config.json`
- **Linux:** `~/.config/claude/claude_desktop_config.json`
1. **配置内容:**
只需复制生成的内容 `mcp_config_claude.json` 将文件保存到Claude Desktop配置文件。安装脚本已正确配置所有路径和设置。
**生成的配置示例:**
{ "mcpServers": { "your-server-name": { "command": "python3", "args": ["kotlin_mcp_server.py"], "cwd": "/absolute/path/to/kotlin-mcp-server", "env": { "PROJECT_PATH": "${workspaceRoot}" } } } }
**✅ 准备使用:** 无需手动更新路径-一切都是预先配置的!
#### **光标IDE**
1. **安装扩展:**
- 与VS代码相同的扩展名(游标基于VS代码)
- Python、Pylint、黑色格式化工具、isort
1. **配置:**
使用相同 `mcp_config_vscode.json` 配置为VS代码。添加到光标 `settings.json`:
{ "mcp.server.configFiles": [ "/absolute/path/to/your/kotlin-mcp-server/mcp_config_vscode.json" ] }
#### **VS代码桥服务器(替代集成)**
对于需要HTTP API访问MCP工具的VS代码扩展,该项目包括一个桥接服务器。
**1.启动网桥服务器:**
Default port (8080)
python3 vscode_bridge.py
Custom port
python3 vscode_bridge.py 8081
With environment configuration
MCP_BRIDGE_HOST=0.0.0.0 MCP_BRIDGE_PORT=8080 python3 vscode_bridge.py
**2.健康检查:**
Test server is running
curl http://localhost:8080/health
Expected response:
{ "status": "healthy", "current_workspace": "/path/to/current/workspace", "available_tools": [ "gradle_build", "run_tests", "create_kotlin_file", "create_layout_file", "analyze_project" ] }
**3.使用桥梁API:**
Call MCP tools via HTTP
curl -X POST http://localhost:8080/ \ -H "Content-Type: application/json" \ -d '{ "tool": "create_kotlin_file", "arguments": { "file_path": "src/main/MyClass.kt", "content": "class MyClass { }" } }'
**4.VS代码扩展集成:**
// In your VS Code extension const response = await fetch('http://localhost:8080/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ tool: 'analyze_project', arguments: { analysis_type: 'architecture' } }) });
const result = await response.json();
**5.配置:**
Environment variables for bridge server
MCP_BRIDGE_HOST=localhost # Server host MCP_BRIDGE_PORT=8080 # Server port VSCODE_WORKSPACE_FOLDER=/path # Override workspace detection
#### **其他IDE**
对于支持MCP的IDE:
- **Vim/Neov:** 使用coc-mcp或类似的mcp插件
- **Emacs:** 安装mcp模式包
- **崇高文本:** 通过包控制安装MCP包
______________________________________________________________________
## �️ **故障排除**
### **常见安装问题**
#### **Python版本兼容性**
Check Python version (must be 3.8+)
python3 --version
If using older Python, install newer version
macOS with Homebrew:
brew install python@3.11
Ubuntu/Debian:
sudo apt update && sudo apt install python3.11
#### **依赖关系安装错误**
Upgrade pip first
python3 -m pip install --upgrade pip
Install with verbose output for debugging
pip install -r requirements.txt -v
Use alternative index if needed
pip install -r requirements.txt -i https://pypi.org/simple/
#### **导入错误**
Verify installation
python3 -c "import kotlin_mcp_server; print('Import successful')"
Check Python path
python3 -c "import sys; print(sys.path)"
Install in development mode
pip install -e .
### **配置问题**
#### **使用新安装程序(推荐)**
大多数配置问题现在都会自动解决:
Regenerate configuration with the enhanced installer
python3 install.py
For specific setup types:
python3 install.py 1 /your/android/project my-server false python3 install.py --help # See all options
#### **传统手动配置问题**
如果您仍在使用旧版本的手动配置:
1. Update to the new installer (recommended)
python3 install.py
2. Or manually find your actual paths (legacy method)
cd /path/to/kotlin-mcp-server && pwd cd /path/to/android/project && pwd
3. Update config files - replace ${MCP_SERVER_DIR} with actual path
Example: Change this
"cwd": "${MCP_SERVER_DIR}"
To this (your actual path)
"cwd": "~/Documents/kotlin-mcp-server"
**💡 专业建议**:新的安装程序完全消除了这些手动步骤!
#### **环境变量问题**
Check if variables are set
env | grep MCP env | grep WORKSPACE
Load environment file manually if needed
source .env
Test variable expansion
echo $MCP_SERVER_DIR echo $WORKSPACE_PATH
#### **MCP服务器未启动**
1. **检查配置文件路径** 在IDE设置中
1. **验证Python解释器** IDE设置中的路径
1. **确保环境变量** 设置正确
1. **检查日志** 有关特定错误消息
#### **IDE插件问题**
VS Code: Reset extension
code --uninstall-extension ms-python.python code --install-extension ms-python.python
JetBrains: Clear caches
File > Invalidate Caches and Restart
#### **VS代码桥服务器问题**
Test bridge server is running
curl http://localhost:8080/health
Check if port is in use
netstat -an | grep 8080 lsof -i :8080
Start bridge server with debug
MCP_BRIDGE_HOST=0.0.0.0 MCP_BRIDGE_PORT=8080 python3 vscode_bridge.py
Test specific tool call
curl -X POST http://localhost:8080/ \ -H "Content-Type: application/json" \ -d '{"tool": "list_tools", "arguments": {}}'
Common fixes:
1. Check firewall settings for port 8080
2. Ensure python3 vscode_bridge.py is running
3. Verify VSCODE_WORKSPACE_FOLDER environment variable
4. Check bridge server logs for errors
#### **权限错误**
macOS/Linux: Fix permissions
chmod +x *.py chmod 755 servers/mcp-process/
Windows: Run as administrator or check file permissions
### **运行时问题**
#### **AI集成失败**
Test local LLM connection
curl http://localhost:11434/api/generate -d '{"model":"llama2","prompt":"test"}'
Verify API keys are set
python3 -c "import os; print('OpenAI key:', os.getenv('OPENAI_API_KEY', 'Not set'))"
#### **文件操作错误**
Check disk space
df -h
Verify write permissions
touch test_file.txt && rm test_file.txt
Check workspace path
ls -la "${WORKSPACE_PATH}"
#### **安全/合规性错误**
Test encryption setup
python3 -c "from cryptography.fernet import Fernet; print('Encryption available')"
Verify compliance mode
python3 -c "import os; print('Compliance:', os.getenv('COMPLIANCE_MODE', 'None'))"
### **已知问题和修复**
#### **GitHub操作构建失败**
如果遇到CI/CD问题:
1. **配置文件:** 确保 `.flake8` 存在(不在 `pyproject.toml`)
1. **GitHub操作:** 更新到最新版本:
- `actions/checkout@v4`
- `actions/setup-python@v4`
- `actions/cache@v4`
1. **代码格式:** 跑 `make format` 修复样式问题
#### **弃用的依赖关系**
Update all dependencies
pip install --upgrade -r requirements.txt
Check for security vulnerabilities
pip audit
Update Python tools
pip install --upgrade black isort flake8 pylint mypy
### **性能问题**
#### **服务器响应缓慢**
Enable performance monitoring
export LOG_LEVEL=DEBUG
Run performance tests
make perf
Profile server startup
python3 -m cProfile kotlin_mcp_server.py
#### **内存使用**
Monitor memory usage
python3 -c "import psutil; print(f'Memory: {psutil.virtual_memory().percent}%')"
Run memory-efficient mode
export MCP_LOW_MEMORY_MODE=true
### **获取帮助**
1. **检查日志:** 看进去 `mcp_security.log` 有关详细的错误信息
1. **运行诊断:** 使用 `python3 comprehensive_test.py --verbose`
1. **验证配置:** 跑 `python3 breaking_change_monitor.py`
1. **测试单个组件:**
# Test core server python3 kotlin_mcp_server.py --test
# Test enhanced features python3 kotlin_mcp_server.py --test
# Test AI integration python3 kotlin_mcp_server.py --test
1. **联系支持:** 报告问题时包括日志、系统信息和错误消息
______________________________________________________________________
## 🌉 **VS代码桥服务器**
VS代码桥服务器为VS代码扩展和其他不能直接使用MCP协议的应用程序提供对MCP工具的HTTP API访问。
### **何时使用网桥服务器**
- **VS代码扩展**:构建需要MCP功能的自定义VS代码扩展时
- **HTTP客户端**:与仅支持HTTP API的工具集成时
- **远程访问**:当您需要从另一台机器访问MCP工具时
- **测试**:使用curl或Postman轻松测试MCP工具
- **Web应用程序**:用于MCP功能的基于网络的界面
### **网桥服务器功能**
#### **工作空间检测**
- 自动检测当前VS代码工作区
- 用途 `VSCODE_WORKSPACE_FOLDER` 环境变量
- 回退到当前工作目录
#### **可用端点**
**健康检查:**
GET /health
Returns: server status, workspace info, available tools
**工具执行:**
POST / Content-Type: application/json
{ "tool": "tool_name", "arguments": { "param1": "value1", "param2": "value2" } }
#### **通过Bridge支持的工具**
- `gradle_build` -构建Android项目
- `run_tests` -执行测试
- `create_kotlin_file` -创建Kotlin源文件
- `create_layout_file` -创建Android布局文件
- `analyze_project` -项目结构分析
- 所有其他MCP工具(请参阅完整列表 `/health`)
### **配置**
#### **环境变量**
Bridge server configuration
MCP_BRIDGE_HOST=localhost # Server host (default: localhost) MCP_BRIDGE_PORT=8080 # Server port (default: 8080)
Workspace configuration
VSCODE_WORKSPACE_FOLDER=/path/to/project # Override workspace detection PROJECT_PATH=/path/to/project # Fallback project path
#### **安全考虑**
For remote access (use with caution)
MCP_BRIDGE_HOST=0.0.0.0 # Allow external connections
For local development only (recommended)
MCP_BRIDGE_HOST=127.0.0.1 # Local connections only
### **使用示例**
#### **启动网桥服务器**
Basic startup
python3 vscode_bridge.py
With custom configuration
MCP_BRIDGE_HOST=localhost MCP_BRIDGE_PORT=8081 python3 vscode_bridge.py
Background mode
python3 vscode_bridge.py &
#### **健康检查**
curl http://localhost:8080/health
Response:
{ "status": "healthy", "current_workspace": "~/AndroidProject", "available_tools": ["gradle_build", "run_tests", ...] }
#### **创建Kotlin文件**
curl -X POST http://localhost:8080/ \ -H "Content-Type: application/json" \ -d '{ "tool": "create_kotlin_file", "arguments": { "file_path": "src/main/kotlin/MainActivity.kt", "package_name": "com.example.app", "class_name": "MainActivity" } }'
#### **运行Gradle构建**
curl -X POST http://localhost:8080/ \ -H "Content-Type: application/json" \ -d '{ "tool": "gradle_build", "arguments": { "task": "assembleDebug", "clean_first": true } }'
#### **格式化Kotlin代码**
curl -X POST http://localhost:8080/ \ -H "Content-Type: application/json" \ -d '{ "tool": "format_code", "arguments": {} }'
#### **运行静态分析**
curl -X POST http://localhost:8080/ \ -H "Content-Type: application/json" \ -d '{ "tool": "run_lint", "arguments": { "lint_tool": "detekt" } }'
#### **生成文档**
curl -X POST http://localhost:8080/ \ -H "Content-Type: application/json" \ -d '{ "tool": "generate_docs", "arguments": { "doc_type": "html" } }'
### **VS代码扩展集成**
#### **Types/JavaScript示例**
interface MCPRequest { tool: string; arguments: Record; }
interface MCPResponse { success?: boolean; result?: any; error?: string; }
class MCPBridgeClient { private baseUrl: string;
constructor(host = 'localhost', port = 8080) { this.baseUrl = http://${host}:${port}; }
async healthCheck(): Promise { const response = await fetch(${this.baseUrl}/health); return response.json(); }
async callTool(tool: string, arguments: Record): Promise { const response = await fetch(this.baseUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ tool, arguments }) }); return response.json(); }
async createKotlinFile(filePath: string, className: string): Promise { return this.callTool('create_kotlin_file', { file_path: filePath, class_name: className }); }
async buildProject(task = 'assembleDebug'): Promise { return this.callTool('gradle_build', { task }); } }
// Usage in VS Code extension const mcpClient = new MCPBridgeClient();
// In extension activation const health = await mcpClient.healthCheck(); console.log('MCP Bridge Status:', health.status);
// Create new Kotlin file const result = await mcpClient.createKotlinFile( 'src/main/kotlin/NewClass.kt', 'NewClass' );
### **网桥服务器故障排除**
#### **常见问题**
Port already in use
netstat -tulpn | grep 8080
Kill process using port: sudo kill -9
Permission denied
sudo ufw allow 8080 # Ubuntu sudo firewall-cmd --add-port=8080/tcp # CentOS
Connection refused
Check if server is running:
ps aux | grep vscode_bridge.py
Test with verbose curl:
curl -v http://localhost:8080/health
#### **调试模式**
Enable debug logging
DEBUG=true python3 vscode_bridge.py
Check server logs
tail -f /tmp/mcp-bridge.log
### **业绩说明**
- **轻量级**:具有低内存占用的最小HTTP服务器
- **工作区感知**:自动使用当前VS代码工作区
- **错误处理**:包含详细信息的优雅错误响应
- **CORS支持**:包括web应用程序的CORS标头
______________________________________________________________________
## 🧪 **测试和质量保证**
该项目包括一个全面的测试和质量保证体系。有关详细的测试信息,请参阅 [`TESTING_GUIDE.md`](TESTING_GUIDE.md).
### **快速测试命令**
Run all tests
make test
Run tests with coverage
make coverage
Run quality checks
make lint
Full CI pipeline
make ci
Check for breaking changes
python breaking_change_monitor.py
### **质量指标**
- **测试覆盖范围:** 最低80%
- **演出** \`
- \[\]安装依赖项: `pip install -r requirements.txt`
- \[\]在中配置环境变量 `.env` 文件
- \[\]安装所需的IDE插件/扩展
- \[\]验证安装: `python3 validate_config.py`
### **基本工具测试**
- \[\]测试项目分析: `{"name": "analyze_project", "arguments": {"analysis_type": "architecture"}}`
- \[\]测试文件创建: `{"name": "create_kotlin_file", "arguments": {"file_path": "Test.kt", "class_name": "Test"}}`
- \[\]测试构建: `{"name": "gradle_build", "arguments": {"task": "assembleDebug"}}`
- \[\]测试AI集成: `{"name": "query_llm", "arguments": {"prompt": "Hello world", "llm_provider": "local"}}`
### **高级功能**
- \[\]设置MVVM架构: `setup_mvvm_architecture`
- \[\]配置依赖注入: `setup_dependency_injection`
- \[\]实现安全功能: `encrypt_sensitive_data`
- \[\]设置合规性(如果需要): `implement_gdpr_compliance` 或 `implement_hipaa_compliance`
- \[\]配置云同步: `setup_cloud_sync`
- \[\]设置外部API: `setup_external_api`
### **测试与质量**
- \[\]生成单元测试: `generate_unit_tests`
- \[\]运行全面测试: `run_tests`
- \[\]执行代码分析: `analyze_code_with_ai`
- \[\]运行棉绒检查: `run_lint`
- \[\]生成文档: `generate_docs`
### **可选集成**
- \[\]测试VS代码桥服务器: `python3 vscode_bridge.py`
- \[\]配置Claude桌面集成
- \[\]设置云存储备份
- \[\]启用AI代码生成功能
**🎉 准备好构建企业级Android应用程序,31个AI增强工具供您使用!**
### 📚 **后续步骤**
1. **探索工具:** 从基本工具开始,如 `analyze_project` 和 `create_kotlin_file`
1. **设置架构:** 使用 `setup_mvvm_architecture` 用于干净的代码结构
1. **添加安全性:** 实施 `encrypt_sensitive_data` 以及合规功能
1. **生成代码:** 利用人工智能工具实现快速开发
1. **测试一切:** 使用 `generate_unit_tests` 和 `run_tests` 质量保证
### 🆘 **获取帮助**
- **工具参考:** 每个工具都有上面详细的参数文档
- **示例:** README中的行业特定示例
- **故障排除:** 包括全面的故障排除部分
- **最佳实践:** 遵循工具使用指南以获得最佳结果
______________________________________________________________________
## 📄 **版本信息**
**当前版本:** `V2.0` -AI增强模块化架构\
**发布日期:** 2025年8月\
**兼容性:** 向后兼容V1.0项目\
**下一版本:** V2.1计划进行小幅增强和错误修复
**发行说明:**
- 🤖 人工智能驱动的代码生成,实现生产就绪
- 🏗️ 模块化架构,可更好地维护
- 🌍 跨平台兼容性的动态配置系统
- ⚡ 增强的性能和可靠性改进
- 🛡️ 高级安全和合规功能
有关详细的版本历史记录,请参阅 **修订历史** 本文档顶部的部分。
______________________________________________________________________
## 🔧 Kotlin Sidecar设置
Kotlin sidecar使用Kotlin analysis API提供AST-aware代码分析和重构功能。
### 建造Sidecar
Navigate to the sidecar directory
cd kotlin-sidecar
Build with Gradle (requires Java 17+)
./gradlew build
Or use gradle wrapper if available
gradle build
### 驾驶Sidecar
Run the sidecar directly
./gradlew runSidecar
Or run the built JAR
java -jar build/libs/kotlin-sidecar-1.0.0.jar
### 侧车协议
sidecar通过stdin/stdout上的NDJSON进行通信:
**请求格式:**
{"tool": "refactorFunction", "input": {"filePath": "...", "functionName": "..."}}
**响应格式:**
{"ok": true, "result": {"patch": "...", "affectedFiles": ["..."]}}
**错误格式:**
{"ok": false, "error": {"code": "ValidationError", "message": "..."}}
______________________________________________________________________
## ⚙️ 环境变量引用
|变量|默认值|描述|
|----------|---------|-------------|
| `MCP_SIDECAR_CMD` | `["java","-jar","kotlin-sidecar.jar"]` |启动Kotlin sidecar的命令|
| `MCP_MAX_RETRIES` | `5` |最大API重试次数|
| `MCP_API_TIMEOUT_MS` | `3000` |API超时(以毫秒为单位)|
| `MCP_RATE_LIMIT_QPS` | `10` |每秒查询速率限制|
| `MCP_AUDIT_DB_PATH` | `./mcp_audit.db` |审核数据库路径|
| `MCP_LOG_LEVEL` | `INFO` |日志记录级别|
| `MCP_ENABLE_TELEMETRY` | `false` |启用遥测采集|
| `MCP_CIRCUIT_BREAKER_THRESHOLD` | `5` |断路器故障阈值|
| `MCP_CIRCUIT_BREAKER_TIMEOUT_MS` | `60000` |断路器复位超时|
### 安全与合规
|变量|描述|
|----------|-------------|
| `MCP_ENCRYPTION_KEY` |用于敏感数据的AES-256加密密钥|
| `MCP_AUDIT_RETENTION_DAYS` |保留审计日志的天数|
| `MCP_GDPR_MODE` |启用GDPR合规功能|
| `MCP_HIPAA_MODE` |启用HIPAA合规功能|
### AI/ML配置
|变量|描述|
|----------|-------------|
| `MCP_LLM_PROVIDER` |法学硕士(openai、anthropic、local)|
| `MCP_LLM_API_KEY` |外部LLM提供程序的API密钥|
| `MCP_LOCAL_LLM_ENDPOINT` |本地LLM服务器的终结点|
| `MCP_AI_MODEL` |要使用的特定AI模型|
### 文件管理
|变量|描述|
|----------|-------------|
| `MCP_BACKUP_RETENTION_DAYS` |保留文件备份的天数|
| `MCP_MAX_BACKUP_SIZE_MB` |最大备份大小(MB)|
| `MCP_SYNC_INTERVAL_SECONDS` |文件同步间隔|
| `MCP_ENCRYPTED_EXTENSIONS` |要自动加密的文件扩展名|
______________________________________________________________________
## 📚 工具目录和示例
### 核心开发工具
#### `refactorFunction`
使用AST感知转换重构Kotlin函数。
{ "name": "refactorFunction", "arguments": { "filePath": "/app/src/main/kotlin/MyClass.kt", "functionName": "calculateTotal", "refactorType": "rename", "newName": "computeTotal", "preview": false } }
#### `formatCode`
使用ktlint或一尘不染格式化Kotlin代码。
{ "name": "formatCode", "arguments": { "targets": ["src/main/kotlin"], "style": "ktlint", "preview": false } }
#### `optimizeImports`
优化和组织Kotlin导入。
{ "name": "optimizeImports", "arguments": { "projectRoot": "/app", "mode": "project", "preview": false } }
### Git工具
#### `gitStatus`
获取Git存储库状态。
{ "name": "gitStatus", "arguments": {} }
#### `gitSmartCommit`
创建智能提交消息。
{ "name": "gitSmartCommit", "arguments": {} }
#### `gitCreateFeatureBranch`
创建新的要素分支。
{ "name": "gitCreateFeatureBranch", "arguments": { "branchName": "user-authentication" } }
### API工具
#### `apiCallSecure`
使用身份验证进行安全的API调用。
{ "name": "apiCallSecure", "arguments": { "apiName": "github", "endpoint": "/repos/owner/repo/issues", "method": "GET", "auth": { "type": "bearer", "token": "ghp_..." } } }
#### `apiMonitorMetrics`
获取API监控指标。
{ "name": "apiMonitorMetrics", "arguments": { "apiName": "github", "windowMinutes": 60 } }
### 生活质量工具
#### `projectSearch`
带上下文的快速grep搜索。
{ "name": "projectSearch", "arguments": { "query": "TODO|FIXME", "includePattern": "*.{kt,java}", "maxResults": 50, "contextLines": 2 } }
#### `todoListFromCode`
解析TODO/FIXME评论。
{ "name": "todoListFromCode", "arguments": { "includePattern": "*.{kt,java,py}", "maxResults": 100 } }
#### `readmeGenerateOrUpdate`
生成或更新README。
{ "name": "readmeGenerateOrUpdate", "arguments": { "forceRegenerate": false } }
#### `buildAndTest`
运行构建并返回测试结果。
{ "name": "buildAndTest", "arguments": { "buildTool": "auto", "skipTests": false } }
#### `dependencyAudit`
审核漏洞的依赖关系。
{ "name": "dependencyAudit", "arguments": {} }
______________________________________________________________________
## 🔒 安全和RBAC
### 基于角色的访问控制
服务器使用以下角色实现了全面的RBAC:
- **管理员**:完全访问所有工具和配置
- **开发者**:访问开发工具(重构、格式化、构建)
- **分析师**:只读访问分析和监控工具
- **审计员**:访问审计跟踪和合规报告
### 速率限制
可配置的速率限制可防止滥用:
- **全球QPS限额**: `MCP_RATE_LIMIT_QPS` (默认值:10)
- **每用户限制**:可按角色配置
- **爆发处理**:用于平滑流量的令牌桶算法
### 遥测
用于使用情况分析的可选遥测数据收集:
- **启用**:设置 `MCP_ENABLE_TELEMETRY=true`
- **收集的数据**:工具使用统计、性能指标
- **隐私**:未收集敏感数据或代码内容
- **选择退出**:默认情况下禁用