🌟 前言:为什么我们需要 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); // 自动支持撤销!
💡 特点
- 安全可控:所有修改经用户确认
- 本地运行:无隐私泄露风险
- 工程友好:基于标准工具链(ESLint)
- 可扩展:轻松支持 TypeScript、Jest 等
这正是 MCP 的核心价值 :AI 不是取代开发者,而是成为可信赖的编程搭档。