MLX驱动的代理RAG系统
Anthropic的“使用MCP执行代码”模式的完整实现,将Claude Code钩子、技能和MLX加速与 Qwen3-VL-2B-思维 为了 增强的推理能力和19倍的存储库分析速度.
🚀 性能指标
| 度量 | 值 |
|---|---|
| 系统吞吐量 | 1200个令牌/秒 (27个实例,每个约44 tok/s) |
| 查询数/小时 | ~8640 |
| 平均响应时间 | 11.2秒 (与vLLM CPU的83.3秒相比) |
| 代币减少 | 98.7% (150k→ 2k个令牌) |
| 每个实例的内存 | 1.2 GB |
| GPU利用率 | 70-90% |
| 功耗 | \ |
cd vibethinker-code-execution npm install chmod +x unified-system.sh
### 3.安装系统捆绑包
Copies MLX servers, MCP server, hooks, and skills into ~/qwen3-claude-system
./unified-system.sh install --install-dir ~/qwen3-claude-system
install命令检查需求,安装Python+节点依赖关系,构建 `mcp-server`,并生成辅助脚本(`setup-env.sh`, `start-system.sh`, `stop-system.sh`).
### 4.启动后端服务
source ~/qwen3-claude-system/setup-env.sh ~/qwen3-claude-system/start-system.sh # or run ./unified-system.sh start ./unified-system.sh status # verifies MCP/MLX/monitor ports
这将引导MLX工作程序(端口8107+)、优化的负载均衡器(端口8090)、运行状况监视器(8092)和MCP服务器(stdio传输)。
### 5.将Claude Code连接到任何存储库
跑吧 `use` 您希望Claude Code编辑的仓库中的命令。
cd /path/to/your/project /path/to/vibethinker-code-execution/unified-system.sh use
`use` (或 `setup-hooks`)写 `.claude/claude_settings.json`,将共享符号链接 `hooks/` 和 `skills/` 目录来自 `~/qwen3-claude-system`,种子 `.claude/workspace/`,并确保MCP堆栈在Claude Code连接之前运行。
### 验证命令
./unified-system.sh health # end-to-end check (throughput + MLX import) npm run health-check # Python diagnostics in scripts/health_check.py npm run setup-mcp # Builds/runs just the MCP server via stdio curl http://localhost:8090/health # Load balancer/monitor endpoint
一旦钩子就位,您就可以启动Claude Code,打开仓库,并发出如下提示 `claude-code "skill: deep-repo-research --focus=security"` 或 `claude-code "Refactor the request handler without breaking auth"`.
## 统一管理脚本
`unified-system.sh` 集中了原始shell脚本用于执行的所有操作。突出显示的命令:
|命令|目的|
|---------|---------|
| `./unified-system.sh install [--install-dir PATH]` |将MLX+MCP资产复制到可移植目录中(默认 `~/qwen3-claude-system`)并安装Node/Python deps。 |
| `./unified-system.sh start / stop / restart` |管理MLX进程、优化的负载均衡器(端口8090)、MCP服务器和监视器。 |
| `./unified-system.sh status` |对端口8090–8092执行轻量级HTTP检查,并确认每个MLX工作端口都有响应。 |
| `./unified-system.sh health` |运行状态检查以及MLX导入验证和吞吐量评分|
| `./unified-system.sh use` |在回购内部,写道 `.claude/claude_settings.json`,符号链接从安装目录中挂钩/技能,并初始化 `.claude/workspace`. |
| `./unified-system.sh setup-hooks` |仅刷新Claude配置(在CI准备仓库时有用)。 |
| `./unified-system.sh deploy` |生成优化配置(`mlx_enhanced_config.json`, `optimized_lb_config.json`)在重新启动服务之前。 |
| `./unified-system.sh clean / test / uninstall` |日志、集成测试或删除安装的维护助手。 |
所有命令接受 `--install-dir`, `--instances`, `--port-base`,以及 `--target-throughput` 覆盖,因此您可以运行多个堆栈或缩减最小的硬件。
## 🎯 使用示例
### 渐进披露API
import * as repo from './servers';
// Automatic progressive disclosure - only loads needed tools const auth = await repo.architectural.synthesizeFindings({ topic: "authentication flow", depth: "comprehensive" });
// Result: 2k token summary vs 150k tokens of raw files console.log(auth.summary); console.log(Analyzed ${auth.metadata.filesCount} files); console.log(Found ${auth.findings.length} insights);
### 自动上下文收集
// SessionStart hook loads repo structure into .claude/context/ // PreToolUse hook gathers file dependencies before edits // PostToolUse hook analyzes impact after changes // Skills activate automatically based on user intent
### 存储库分析
Deep repository research
claude-code "Research the authentication system in this repo"
Architectural analysis
claude-code "Analyze the dependency injection patterns"
Context-aware editing
claude-code "Update the user service without breaking auth"
## 🔧 配置
### MCP/MLX配置
`mlx-servers/config.json` 是调整模型参数、负载均衡器调优和监视行为的规范位置。默认文件随附:
{ "mlx_servers": { "instances": 27, "base_port": 8107, "model_path": "lmstudio-community/Qwen3-VL-2B-Thinking-MLX-8bit", "quantization": "8bit", "max_tokens": 32768, "temperature": 1.0, "top_p": 0.95, "top_k": 20, "repetition_penalty": 1.0, "presence_penalty": 1.5, "gpu_memory_fraction": 0.85, "batch_size": 6 }, "load_balancer": { "algorithm": "least_connections", "health_check_interval": 60, "circuit_breaker": { "failure_threshold": 5, "recovery_timeout": 600000 } }, "performance": { "target_tokens_per_second": 55, "request_timeout": 180000, "keep_alive": true, "compression": true } }
更新内部文件 `~/qwen3-claude-system/mlx-servers/` 安装后,通过重新启动 `./unified-system.sh restart`.
### Claude代码设置
`./unified-system.sh use` 写 `.claude/claude_settings.json` 在目标仓库中。生成的配置如下( `$QWEN3_SYSTEM_DIR` 环境变量由设置 `setup-env.sh`).
{ "hooks": { "PreToolUse": [ { "matcher": "Write|Edit|Read", "hooks": [ { "type": "command", "command": "node $QWEN3_SYSTEM_DIR/hooks/pre-tool-use/context-gatherer.js" }, { "type": "command", "command": "node $QWEN3_SYSTEM_DIR/hooks/pre-tool-use/security-validator.js" } ] } ], "PostToolUse": [ { "matcher": "Write|Edit", "hooks": [ { "type": "command", "command": "node $QWEN3_SYSTEM_DIR/hooks/post-tool-use/analyze-changes.js" }, { "type": "command", "command": "node $QWEN3_SYSTEM_DIR/hooks/post-tool-use/update-context.js" }, { "type": "command", "command": "node $QWEN3_SYSTEM_DIR/hooks/post-tool-use/run-tests.js" } ] } ], "SessionStart": [ { "hooks": [ { "type": "command", "command": "node $QWEN3_SYSTEM_DIR/hooks/session-start.js" } ] } ] }, "skills": { "auto_load": true, "skills_path": "$QWEN3_SYSTEM_DIR/skills" }, "mcp": { "transport": "stdio", "server_url": "http://localhost:8090", "model_config": { "temperature": 1.0, "top_p": 0.95, "max_tokens": 32768 } } }
## 📊 性能优化
### MLX型号配置
- **量化**:8位用于增强推理,具有良好的内存效率
- **模型**:Qwen3-VL-2B-具有先进多模态能力的思维
- **批量大小**:针对M3 Max GPU进行了优化(每个实例6个批次)
- **上下文长度**:每个实例32768个令牌
- **负载平衡**:具有健康检查功能的智能循环
- **生成**:优化了创造性和分析任务的参数
### 缓存策略
- **查询结果**:LRU驱逐1小时TTL
- **依赖图**:跨会话持续
- **上下文摘要**:压缩和索引
- **工具定义**:延迟加载预取
### 内存管理
- **GPU内存**:每个MLX实例1.2GB(总共27×=~32GB)
- **系统记忆体**:2GB用于Node.js进程
- **高速缓冲存储器**:1GB用于查询结果
- **总占地面积**:整个系统约35GB
- **增强推理**:更大的模型提供了更好的工具使用和规划
## 🔒 安全特性
- **沙盒执行**:所有代码都在隔离环境中运行
- **权限验证**:钩子验证敏感操作
- **输入消毒**:所有用户输入都经过验证
- **审计日志**:完成活动跟踪
- **速率限制**:防止滥用和资源枯竭
## 🛠️ 发展
### 测试覆盖率
该项目保持全面的测试覆盖率 **239测试** 跨多个模块:
Run all tests
cd mcp-server && pnpm test
Run with coverage
pnpm test -- --coverage
Run specific test files
pnpm vitest run tests/tools/registry.test.ts
|测试套件|测试|描述|
|------------|-------|-------------|
| `registry.test.ts` |41 |工具注册表、错误处理、指标|
| `searchByQuery.test.ts` |32 |基于Ripgrep的代码搜索|
| `detectIssues.test.ts` |32 |代码气味和错误检测|
| `findPatterns.test.ts` |34|反模式检测|
| `analyzeImports.test.ts` |31 |进口分析、周期检测|
| `analyzeFile.test.ts` |22 |文件复杂性分析|
| `utils.test.ts` |30 |实用函数和错误处理|
| `hook-lifecycle.test.ts` |17 |挂钩集成测试|
### 添加新技能
1. 在中创建目录 `skills/`
1. 添加 `SKILL.md` 使用YAML frontmatter
1. 实现TypeScript逻辑
1. 在中添加资源 `resources/` 子目录
1. 使用Claude代码进行测试
### 延伸挂钩
1. 在适当的目录中创建挂钩文件
1. 实现事件处理逻辑
1. 添加到配置文件
1. 用真实场景进行测试
### 添加工具
工具遵循具有内置错误处理的结构化定义模式:
import { z } from 'zod'; import { ToolDefinition } from '../../types.js'; import { validatePath, logger, ErrorCodes, createToolFailure } from '../../utils.js';
export const myTool: ToolDefinition = { name: 'myTool', description: 'Description of what the tool does', category: 'repo-search', // or 'code-analysis', 'architectural', 'context-building' version: '1.0.0', capabilities: ['read-files', 'pattern-matching'], resourceHints: { estimatedMemoryMB: 50, estimatedTimeMs: 3000, cpuIntensive: false, }, inputSchema: z.object({ path: z.string().describe('Path to analyze'), options: z.object({ depth: z.number().default(2), }).optional(), }), handler: async (args) => { const validPath = await validatePath(args.path); // Implementation... return { result: 'success', data: analysisResult }; }, tags: ['search', 'analysis'], complexity: 'moderate', externalDependencies: ['ripgrep'], npmDependencies: [], internalDependencies: ['../../utils.js:validatePath'], };
**添加工具的步骤:**
1. 在中创建工具文件 `mcp-server/src/tools/definitions//`
1. 从该类别导出 `index.ts`
1. ToolRegistry在启动时自动注册工具
1. 在中编写单元测试 `tests/tools//`
1. 测试与MCP服务器的集成
### 工具注册表功能
增强 `ToolRegistry` 提供:
- **结构化错误处理**:所有工具错误都包括错误代码、消息和恢复提示
- **执行指标**:跟踪每个工具的成功/失败率、执行时间和错误
- **健康监测**:使用检查注册表运行状况 `registry.isHealthy()`
- **类型安全结果**: `executeTool()` 回报 `ToolResult` 具有成功/错误状态
// Execute tool with structured result const result = await registry.executeTool('searchByQuery', { query: 'function' });
if (result.success) { console.log(result.data); // Tool output console.log(result.metadata); // Execution time, version } else { console.log(result.error?.code); // Error code (e.g., 'TOOL_NOT_FOUND') console.log(result.error?.message); // Human-readable message console.log(result.error?.recoveryHint); // Suggested fix }
// Get metrics for monitoring const metrics = registry.getToolMetrics('searchByQuery'); console.log(Success rate: ${metrics.successCount / metrics.totalCalls});
// Health check const health = registry.isHealthy(); if (!health.healthy) { console.log('Issues:', health.issues); }
## 📈 监控
### 健康检查
System health
npm run health-check
MLX instances
pm2 list
Performance metrics
curl http://localhost:8107/metrics
### 日志记录
- **应用程序日志**: `~/.pm2/logs/`
- **MLX日志**: `./mlx-servers/logs/`
- **挂钩原木**: `./workspace/logs/`
- **审计日志**: `./workspace/audit/`
## 🤝 贡献
1. 复刻仓库
1. 创建特征分支
1. 添加新功能的测试
1. 提交拉取请求
1. 更新文档
## 📄 许可证
MIT许可证-有关详细信息,请参阅许可证文件
## 🙏 致谢
- MCP和克劳德密码的拟人化
- 苹果MLX框架
- 工具和库的开源社区
______________________________________________________________________
**内置于❤️ 通过VibeThinker** | **由Qwen3-VL-2B-Thinking提供技术支持** | **性能:快约15倍,代币减少98.7%**