手把手实现一个前端 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 不是取代开发者,而是成为可信赖的编程搭档。


相关推荐
yz_aiks1 小时前
Claude Code Skills 团队怎么共享:.claude/skills 提交 git 还是建私有插件市场(2.1.299 实测 5 个坑)
人工智能·ai编程·开发工具·团队协作·claude code
AAA修煤气灶刘哥1 小时前
GLM-5.4 到了什么水平?和 Kimi、DeepSeek、GPT 放在一起看
人工智能·llm
小虎AI生活1 小时前
朋友圈发了没人理?这个AI技能一句话甩你4个版本,做私域的都能用
人工智能·超级个体·青玥ai
龙腾AI白云1 小时前
多源数据融合:把零散信号拼成一致图景
大数据·人工智能·python·机器学习·知识图谱
aimartec2 小时前
不动老旧 ERP 核心总账,如何以高性价比方案落地外勤与车间移动协同?
人工智能
艾派森2 小时前
深度学习实战-基于VGG19的健康和白化珊瑚图像分类识别模型
人工智能·python·深度学习·分类
Csvn2 小时前
让 AI 少返工:任务卡六要素与四维验收怎么写
人工智能
老纪的技术唠嗑局2 小时前
新增项目知识库,网关也能帮 Agent 找回记忆|PowerContext v1.6.0 发布
人工智能
用户842558130872 小时前
插值选错,峰值就没了
人工智能
小宋10212 小时前
embedding 返回全零向量,索引却照收不误:入库前的向量健康门禁、隔离重算与召回恢复判据
linux·服务器·网络·人工智能