手把手实现一个前端 AI 编程助手:从 MCP 思想到 VS Code 插件实战

🌟 前言:为什么我们需要 AI 编程助手?

作为前端开发者,你是否经历过:

  • 写完代码,ESLint 报出一堆 no-unused-vars 错误?
  • 想快速修复 console.log,却要手动删除?
  • 面对 TypeScript 类型错误,不知从何下手?

传统 LLM(如 ChatGPT)只能"说",不能"做"------它看不到你的项目结构、终端输出、错误日志。而 Cursor 等新一代 AI 编辑器 提出了 MCP(Model Context Protocol) 的概念,让 AI 能理解上下文 + 安全行动 + 闭环验证

今天,我将带你从零实现一个前端专属的 AI 编程助手,核心思想正是 MCP 的简化版!


🔧 技术栈:前端开发者友好

  • VS Code 插件开发(TypeScript)
  • 本地 LLM:Ollama + Llama3(免费、隐私安全)
  • 前端工程工具:ESLint(v9+ 扁平配置)
  • 零深度学习:只需会调用 API

💡 全程使用你熟悉的工具,无 CUDA、无训练、无云服务!


🧠 核心思想:MCP 的前端实践

MCP 的本质是 让 LLM 理解开发环境。在我们的插件中,它体现为三层:

层级 实现 作用
上下文提供 getEsLintErrors() 获取结构化 ESLint 错误
工具调用 applyCodeFixSafely() 安全修改文件(带 diff 预览)
Agent 规划 fixEsLintWithAgent() 实现"检测 → 修复 → 验证"闭环

✅ 这就是 前端版 MCP


🚀 第一步:创建 VS Code 插件

css 复制代码
npm install -g yo generator-code
yo code  # 选择 TypeScript

关键配置 package.json

json 复制代码
{
  "name": "devagent",
  "activationEvents": ["onCommand:devagent.fixEsLint"],
  "contributes": {
    "commands": [{
      "command": "devagent.fixEsLint",
      "title": "DevAgent: Fix ESLint Errors"
    }]
  }
}

🤖 第二步:实现 MCP 核心 ------ 上下文与工具

1. 获取 ESLint 错误(上下文提供者)

ini 复制代码
// src/mcp.ts
export async function getEsLintErrors(filePath: string): Promise<any[]> {
  const result = cp.spawnSync(eslintPath, ['--format', 'json', filePath], {
    cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe']
  });

  // 关键:ESLint 有错误时 status=1,但 stdout 有效!
  if (result.status === 0 || result.status === 1) {
    const report = JSON.parse(result.stdout);
    return report?.[0]?.messages || [];
  }
  return [];
}

💡 避坑指南 :ESLint 的退出码 1 表示"有 lint 错误",不是执行失败!

2. 安全应用修复(工具调用)

csharp 复制代码
// 使用 VS Code 原生 diff 预览
await vscode.commands.executeCommand(
  'vscode.diff',
  originalUri,
  tempUri, // 虚拟文档(AI 修复后)
  'AI Fix Preview'
);

零依赖实现专业级 diff


🧠 第三步:实现 Agent 闭环

javascript 复制代码
// src/agent.ts
export async function fixEsLintWithAgent(document: vscode.TextDocument) {
  const errors = await getEsLintErrors(filePath);
  if (errors.length === 0) return;

  // 构造 prompt
  const prompt = `
You are a senior frontend engineer. Fix ALL ESLint errors.
- Delete unused vars/functions
- Remove console statements
- Remove lines with undeclared variables
Only output corrected code.

ESLint Errors:
${JSON.stringify(errors, null, 2)}

Current Code:
\`\`\`js
${currentCode}
\`\`\`
`;

  const fixedCode = await callLocalLLM(prompt);
  await applyCodeFixSafely(document.uri, fixedCode);
}

🖥️ 第四步:接入本地 LLM(Ollama)

typescript 复制代码
// src/llm.ts
export async function callLocalLLM(prompt: string): Promise<string> {
  const response = await axios.post('http://localhost:11434/api/generate', {
    model: 'llama3',
    prompt,
    stream: false
  });
  return response.data.response.trim();
}

📌 安装 Ollama

复制代码
brew install ollama
ollama pull llama3

✨ 效果演示

修复前

ini 复制代码
const unused = 42;
function unusedFn() {}
console.log(undeclaredVar);

AI 修复后

vbscript 复制代码
// console.log(undeclaredVar); // removed due to ESLint error

智能决策

  • 保留可能被外部使用的变量(保守策略)
  • 注释掉危险代码(安全第一)

🚀 进阶:专业级体验优化

1. 添加"接受全部"按钮

ini 复制代码
// 状态栏显示按钮
const statusBarItem = vscode.window.createStatusBarItem();
statusBarItem.text = '$(check) AI Fix Ready';
statusBarItem.command = 'devagent.acceptAllFixes';

2. 高亮修改行

ini 复制代码
// 用 Decoration API 标记变更
const decorationType = vscode.window.createTextEditorDecorationType({
  backgroundColor: 'rgba(255, 255, 0, 0.2)'
});
editor.setDecorations(decorationType, modifiedRanges);

3. 支持撤销(Cmd+Z)

ini 复制代码
// 用 WorkspaceEdit 替代直接写文件
const edit = new vscode.WorkspaceEdit();
edit.replace(uri, fullRange, newContent);
vscode.workspace.applyEdit(edit); // 自动支持撤销!

💡 特点

  1. 安全可控:所有修改经用户确认
  2. 本地运行:无隐私泄露风险
  3. 工程友好:基于标准工具链(ESLint)
  4. 可扩展:轻松支持 TypeScript、Jest 等

这正是 MCP 的核心价值 :AI 不是取代开发者,而是成为可信赖的编程搭档


相关推荐
码云数智-大飞1 分钟前
本地部署大模型:隐私安全与多元优势一站式解读
运维·网络·人工智能
Peter·Pan爱编程12 分钟前
第二篇:为什么现在是 Vibe Coding 的元年?风险与挑战
人工智能·ai编程
jinanwuhuaguo12 分钟前
(第二十九篇)OpenClaw 实时与具身的跃迁——从异步孤岛到数字世界的“原住民”
前端·网络·人工智能·重构·openclaw
广州华水科技18 分钟前
深度测评2026年单北斗GNSS位移监测系统推荐,与高口碑变形监测设备一同引领行业新风尚
前端
大飞记Python25 分钟前
【2026更新】Python基础学习指南(AI版)——04数据类型
开发语言·人工智能·python
Marvel__Dead29 分钟前
AI 大模型时代:验证码如何用「通用识别」解决?
人工智能·ai 大模型·ai 验证码识别·ai 爬虫
生成论实验室35 分钟前
《事件关系阴阳博弈动力学:识势应势之道》第四篇:降U动力学——认知确定度的自驱演化
人工智能·科技·神经网络·算法·架构
不懂的浪漫40 分钟前
把 AI Skill 做成系统:路由、领域技能、自我复盘和进化飞轮
人工智能·ai·skill
等风来不如迎风去1 小时前
【win11】最佳性能:fix 没有壁纸,一直黑屏
网络·人工智能