Skip to main content
Glama

refactor

Analyze code to provide refactoring suggestions and implementation plans for improving readability, reducing complexity, or extracting functions.

Instructions

【重构建议】分析代码并提供重构建议和实施计划

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeNo需要重构的代码
goalNo重构目标:improve_readability, reduce_complexity, extract_function 等

Implementation Reference

  • The core handler function for the 'refactor' tool. It receives args with 'code' and optional 'goal', constructs an elaborate prompt guiding an LLM through code smell identification, refactoring techniques, step-by-step plan, and returns it as MCP content.
    export async function refactor(args: any) { try { const code = args?.code || ""; const goal = args?.goal || ""; // improve_readability, reduce_complexity, extract_function, etc. const message = `请为以下代码提供重构建议: 📝 **代码内容**: ${code || "请提供需要重构的代码"} 🎯 **重构目标**:${goal || "全面优化"} --- ## 重构分析流程 ### 第一步:识别代码坏味道 **常见问题**: 1. **重复代码(Duplicated Code)** - 相同或相似的代码出现多次 - 建议:提取公共函数/方法 2. **过长函数(Long Function)** - 函数超过 30 行 - 建议:拆分为多个小函数 3. **过大类(Large Class)** - 类职责过多 - 建议:按职责拆分类 4. **过长参数列表(Long Parameter List)** - 参数超过 3-4 个 - 建议:使用对象封装参数 5. **复杂条件判断(Complex Conditional)** - 嵌套超过 3 层 - 建议:提前返回、使用策略模式 6. **魔法数字(Magic Numbers)** - 硬编码的数字 - 建议:使用常量 7. **紧耦合(Tight Coupling)** - 模块间依赖过强 - 建议:依赖注入、接口抽象 ### 第二步:重构建议 **优先级分类**: - 🔴 **Critical**:严重影响可维护性 - 🟡 **Important**:建议尽快处理 - 🟢 **Nice-to-have**:可选优化 --- ## 重构技术清单 ### 1️⃣ 提取函数(Extract Function) **场景**:一段代码可以被独立理解 **示例**: \`\`\`typescript // Before function processOrder(order) { // 验证订单 if (!order.id || !order.items || order.items.length === 0) { throw new Error('Invalid order'); } // 计算总价 let total = 0; for (const item of order.items) { total += item.price * item.quantity; } // 应用折扣 if (order.coupon) { total = total * (1 - order.coupon.discount); } return total; } // After function processOrder(order) { validateOrder(order); const subtotal = calculateSubtotal(order.items); const total = applyDiscount(subtotal, order.coupon); return total; } function validateOrder(order) { if (!order.id || !order.items || order.items.length === 0) { throw new Error('Invalid order'); } } function calculateSubtotal(items) { return items.reduce((sum, item) => sum + item.price * item.quantity, 0); } function applyDiscount(amount, coupon) { return coupon ? amount * (1 - coupon.discount) : amount; } \`\`\` ### 2️⃣ 简化条件表达式 **技巧**: - 使用提前返回(Early Return) - 合并条件 - 使用三元运算符 - 策略模式替代 switch **示例**: \`\`\`typescript // Before function getDiscount(user) { if (user) { if (user.isPremium) { if (user.orderCount > 10) { return 0.3; } else { return 0.2; } } else { return 0.1; } } else { return 0; } } // After function getDiscount(user) { if (!user) return 0; if (!user.isPremium) return 0.1; return user.orderCount > 10 ? 0.3 : 0.2; } \`\`\` ### 3️⃣ 引入参数对象 **场景**:参数过多 **示例**: \`\`\`typescript // Before function createUser(name, email, age, address, phone, country) { // ... } // After interface UserData { name: string; email: string; age: number; address: string; phone: string; country: string; } function createUser(userData: UserData) { // ... } \`\`\` ### 4️⃣ 替换魔法数字 **示例**: \`\`\`typescript // Before if (status === 1) { // ... } else if (status === 2) { // ... } // After enum OrderStatus { PENDING = 1, PROCESSING = 2, COMPLETED = 3 } if (status === OrderStatus.PENDING) { // ... } else if (status === OrderStatus.PROCESSING) { // ... } \`\`\` ### 5️⃣ 组合函数调用 **示例**: \`\`\`typescript // Before const data = getData(); const filtered = filterData(data); const sorted = sortData(filtered); const formatted = formatData(sorted); // After const result = getData() .then(filterData) .then(sortData) .then(formatData); // Or using pipe const result = pipe( getData, filterData, sortData, formatData )(); \`\`\` --- ## 重构计划模板 ### 🎯 重构目标 简要说明重构的目的和预期效果 ### 📋 问题清单 1. **问题 1**:重复代码 - 位置:第 10-20 行、第 50-60 行 - 影响:可维护性差 - 优先级:🔴 Critical 2. **问题 2**:函数过长 - 位置:processData() 函数 - 影响:难以理解和测试 - 优先级:🟡 Important ### 🔧 重构步骤 **步骤 1:准备** - [x] 确保测试覆盖率 > 80% - [x] 备份当前代码 - [x] 创建重构分支 **步骤 2:小步重构** 1. 提取 calculateTotal 函数 - 风险:低 - 预计时间:10 分钟 - 测试:运行单元测试 2. 简化条件判断 - 风险:低 - 预计时间:15 分钟 - 测试:运行集成测试 3. 引入参数对象 - 风险:中 - 预计时间:30 分钟 - 测试:全量测试 **步骤 3:验证** - [ ] 所有测试通过 - [ ] 代码审查 - [ ] 性能对比 - [ ] 部署到测试环境 ### ⚠️ 风险评估 **高风险操作**: - 修改公共 API - 改变数据结构 - 调整核心算法 **降低风险的措施**: - 渐进式重构(小步快跑) - 每步都运行测试 - 保持功能不变 - Code Review ### 📊 预期收益 **可维护性**:⬆️ 30% - 代码行数减少 20% - 圈复杂度降低 40% **可测试性**:⬆️ 50% - 函数职责单一 - 依赖可注入 **性能**:⬆️ 10% - 减少重复计算 - 优化算法复杂度 --- 现在请分析代码,提供详细的重构建议和实施计划。`; return { content: [ { type: "text", text: message, }, ], }; } catch (error) { const errorMessage = error instanceof Error ? error.message : String(error); return { content: [ { type: "text", text: `❌ 重构分析失败: ${errorMessage}`, }, ], isError: true, }; } }
  • Input schema and metadata definition for the 'refactor' tool, registered in ListToolsRequestSchema handler.
    { name: "refactor", description: "【重构建议】分析代码并提供重构建议和实施计划", inputSchema: { type: "object", properties: { code: { type: "string", description: "需要重构的代码", }, goal: { type: "string", description: "重构目标:improve_readability, reduce_complexity, extract_function 等", }, }, required: [], }, },
  • Re-export of the refactor handler from its implementation file, making it available for import in src/index.ts.
    export { refactor } from "./refactor.js";
  • src/index.ts:495-496 (registration)
    Dispatch registration in the CallToolRequestSchema switch statement, invoking the refactor handler when the tool name matches.
    case "refactor": return await refactor(args);
  • src/index.ts:33-264 (registration)
    Registration of the tool in the list of available tools returned by ListToolsRequestSchema.
    server.setRequestHandler(ListToolsRequestSchema, async () => { return { tools: [ { name: "detect_shell", description: "【套壳鉴定】执行套壳探针检测,返回 JSON 指纹", inputSchema: { type: "object", properties: { nonce: { type: "string", description: "可选的随机字符串用于哈希校验,默认为 iclaude-4.5|2025-10-25|guyu|boot", }, skip_network: { type: "boolean", description: "是否跳过网络探测(默认 false)", }, }, required: [], }, }, { name: "init_setting", description: "【初始化配置】在 .cursor/settings.json 中写入推荐的 AI 配置", inputSchema: { type: "object", properties: { project_path: { type: "string", description: "项目根目录的完整路径(默认使用当前工作区路径)", }, }, required: [], }, }, { name: "init_project", description: "【初始化工程】按照 Spec-Driven Development 方式创建项目结构和任务分解,参考 https://github.com/github/spec-kit", inputSchema: { type: "object", properties: { input: { type: "string", description: "项目需求描述(可以是文字描述或文件内容)", }, project_name: { type: "string", description: "项目名称", }, }, required: [], }, }, { name: "gencommit", description: "【生成提交】分析代码变更并生成规范的 Git commit 消息(支持 emoji)", inputSchema: { type: "object", properties: { changes: { type: "string", description: "代码变更内容(可选,默认使用 git diff)", }, type: { type: "string", description: "提交类型:fixed, fix, feat, docs, style, chore, refactor, test", }, }, required: [], }, }, { name: "debug", description: "【调试助手】分析错误并生成调试策略和解决方案", inputSchema: { type: "object", properties: { error: { type: "string", description: "错误信息(错误消息、堆栈跟踪)", }, context: { type: "string", description: "相关代码或场景描述", }, }, required: [], }, }, { name: "genapi", description: "【生成文档】为代码生成 API 文档(支持 Markdown、OpenAPI、JSDoc 格式)", inputSchema: { type: "object", properties: { code: { type: "string", description: "需要生成文档的代码", }, format: { type: "string", description: "文档格式:markdown, openapi, jsdoc(默认 markdown)", }, }, required: [], }, }, { name: "code_review", description: "【代码审查】全面审查代码质量、安全性、性能和最佳实践", inputSchema: { type: "object", properties: { code: { type: "string", description: "需要审查的代码", }, focus: { type: "string", description: "审查重点:quality, security, performance, all(默认 all)", }, }, required: [], }, }, { name: "gentest", description: "【生成测试】为代码生成完整的测试用例(支持 Jest/Vitest/Mocha)", inputSchema: { type: "object", properties: { code: { type: "string", description: "需要测试的代码", }, framework: { type: "string", description: "测试框架:jest, vitest, mocha(默认 jest)", }, }, required: [], }, }, { name: "genpr", description: "【生成 PR】分析变更并生成规范的 Pull Request 描述", inputSchema: { type: "object", properties: { branch: { type: "string", description: "分支名称", }, commits: { type: "string", description: "Commit 历史", }, }, required: [], }, }, { name: "check_deps", description: "【依赖检查】分析项目依赖的健康度(版本、安全漏洞、体积)", inputSchema: { type: "object", properties: {}, required: [], }, }, { name: "gendoc", description: "【生成注释】为代码生成详细的 JSDoc/TSDoc 注释", inputSchema: { type: "object", properties: { code: { type: "string", description: "需要生成注释的代码", }, style: { type: "string", description: "注释风格:jsdoc, tsdoc, javadoc(默认 jsdoc)", }, lang: { type: "string", description: "语言:zh, en(默认 zh)", }, }, required: [], }, }, { name: "genchangelog", description: "【生成 Changelog】根据 commit 历史生成 CHANGELOG.md", inputSchema: { type: "object", properties: { version: { type: "string", description: "版本号(如:v1.2.0)", }, from: { type: "string", description: "起始 commit/tag", }, to: { type: "string", description: "结束 commit/tag(默认 HEAD)", }, }, required: [], }, }, { name: "refactor", description: "【重构建议】分析代码并提供重构建议和实施计划", inputSchema: { type: "object", properties: { code: { type: "string", description: "需要重构的代码", }, goal: { type: "string", description: "重构目标:improve_readability, reduce_complexity, extract_function 等", }, }, required: [], }, },

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/mybolide/mcp-probe-kit'

If you have feedback or need assistance with the MCP directory API, please join our Discord server