前言
随着大型语言模型(LLM)的快速发展,如何让AI模型更好地理解和参与开发工作流程成为了一个重要议题。MCP协议就是为解决这一问题而生的一种创新方案。本文将介绍MCP协议的基本概念、工作原理及其在实际开发中的应用,帮助大家快速入门并开始使用这一技术。
什么是MCP协议
定义与背景
MCP (Model Context Protocol) 是一个开源协议,设计用于改善AI模型与应用程序之间的交互方式。它由Authropic团队开发,旨在使模型能够更好地理解和操作代码库,从而提高AI辅助编程的效率和准确性。
传统上,当我们使用如ChatGPT这样的AI助手进行编程时,我们需要手动复制代码片段并一一描述文件结构,这种方式效率低下且容易出错。MCP协议通过提供结构化的上下文信息,使模型能够直接”看到”整个项目,就像人类开发者一样工作。
核心概念
MCP协议主要包含以下核心概念:
Protocol Buffer:使用Protocol Buffers (protobuf)作为通信格式,确保了消息的高效传输和良好的向后兼容性。
上下文信息:MCP提供了丰富的上下文信息,包括:
- 文件系统结构
- 代码内容
- 工作目录
- 命令行环境
- Git状态
请求与响应:MCP协议定义了标准化的请求与响应格式,使得应用程序和AI模型能够无缝交流。
工具函数:MCP允许定义和使用工具函数,使AI能够执行特定操作,如计算、查询和数据处理。
MCP协议的工作原理
通信流程
MCP协议的通信流程主要如下:
1 2 3 4 5 6
| +-------------+ +-------------+ | | MCP Request | | | Application | -----------------> | AI Model | | | <----------------- | | | | MCP Response | | +-------------+ +-------------+
|
- 应用程序(如Cursor编辑器)通过MCP协议向AI模型发送请求,请求中包含当前项目的上下文信息。
- AI模型接收请求,处理上下文信息,并生成响应。
- 应用程序接收响应并展示给用户。
协议格式
MCP消息采用Protocol Buffers格式,一个典型的MCP请求包含以下字段:
1 2 3 4 5 6 7 8
| message MCPRequest { string query = 1; repeated File files = 2; string current_file_path = 3; WorkingDirectory working_dir = 4; CommandLine command_line = 5; GitState git_state = 6; }
|
响应则通常包含:
1 2 3 4 5
| message MCPResponse { string answer = 1; repeated FileEdit file_edits = 2; repeated Command commands = 3; }
|
为什么使用MCP协议
优势与特点
结构化上下文:MCP提供了结构化的项目上下文,使AI模型能够理解整个代码库。
跨平台兼容:作为一个开放标准,MCP可以在不同平台和工具间无缝工作。
智能代码操作:模型可以直接建议代码修改、执行命令等,而不仅仅是生成文本回复。
开源和可扩展:作为一个开源协议,社区可以不断改进和扩展其功能。
减少上下文切换:开发者无需频繁在编辑器和AI助手之间切换。
工具集成:MCP支持自定义工具函数,使AI能够执行计算、搜索和其他操作。
与传统方法的对比
| 特性 |
传统AI交互 |
MCP协议 |
| 代码上下文 |
需手动复制粘贴 |
自动提供完整项目结构 |
| 文件访问 |
有限且不直接 |
可访问整个项目文件 |
| 代码编辑 |
生成建议,需手动实现 |
可直接提出结构化的编辑建议 |
| 上下文丢失 |
经常发生 |
持续维护项目上下文 |
| 多文件处理 |
困难 |
高效处理多文件关系 |
| 工具执行 |
不支持 |
可以调用自定义工具 |
如何创建MCP程序
下面我们将通过实例演示如何创建一个支持MCP协议的程序。
环境准备
首先需要安装必要的依赖:
对于JavaScript/TypeScript项目:
1
| npm install @mcp/protocol @mcp/server
|
对于Python项目:
项目结构示例
一个典型的MCP项目结构如下:
1 2 3 4 5 6 7
| mcp_project/ ├── .git/ ├── .gitignore ├── .python-version ├── main.py # 主程序入口 ├── pyproject.toml # 项目配置 └── README.md # 项目说明
|
Python实现MCP服务器
以下是一个基于Python的MCP服务器实现示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| import json import sys from pathlib import Path from typing import Any, Dict, List, Optional
from mcp_server import MCPServer, MCPTools, Request, Response
def calculate_bmi(height: float, weight: float) -> str: """计算BMI值并返回健康状态评估""" bmi = weight / (height * height) if bmi < 18.5: status = "偏瘦" elif bmi < 24: status = "正常" elif bmi < 28: status = "偏胖" else: status = "肥胖" return f"您的BMI值为: {bmi:.2f},健康状态: {status}"
def list_files(directory: str) -> List[str]: """列出指定目录下的所有文件""" path = Path(directory) if not path.exists() or not path.is_dir(): return ["目录不存在或不是有效目录"] return [str(file.name) for file in path.iterdir()]
def get_weather(city: str) -> str: """获取指定城市的天气信息""" weather_data = { "北京": "晴朗,23°C", "上海": "多云,25°C", "广州": "小雨,28°C", "深圳": "晴朗,30°C" } return f"{city}的天气: {weather_data.get(city, '未知天气信息')}"
def convert_currency(amount: float, from_currency: str, to_currency: str) -> str: """将一种货币转换为另一种货币""" rates = { "CNY": {"USD": 0.14, "EUR": 0.13, "JPY": 20.82}, "USD": {"CNY": 7.15, "EUR": 0.92, "JPY": 149.08}, "EUR": {"CNY": 7.80, "USD": 1.09, "JPY": 162.60}, "JPY": {"CNY": 0.048, "USD": 0.0067, "EUR": 0.0062} } if from_currency not in rates or to_currency not in rates[from_currency]: return "不支持的货币转换" converted = amount * rates[from_currency][to_currency] return f"{amount} {from_currency} = {converted:.2f} {to_currency}"
def handle_request(request: Request) -> Response: """处理MCP请求并返回响应""" query = request.query answer = f"收到您的问题: {query}\n\n" answer += "我可以帮助您处理代码问题,您也可以使用以下工具函数:\n" answer += "1. calculate_bmi - 计算BMI值\n" answer += "2. list_files - 列出目录文件\n" answer += "3. get_weather - 获取城市天气\n" answer += "4. convert_currency - 货币转换\n" return Response(answer=answer)
def main(): """主函数,启动MCP服务器""" tools = MCPTools() tools.register("calculate_bmi", calculate_bmi) tools.register("list_files", list_files) tools.register("get_weather", get_weather) tools.register("convert_currency", convert_currency) server = MCPServer( handle_request=handle_request, tools=tools, project_managed=True, name="多功能助手" ) server.start() print("MCP服务器已启动,等待请求...")
if __name__ == "__main__": main()
|
可以使用@mcp.tool() 装饰器来实现MCP工具的创建和实现
将以上可以修改为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import mcp
@mcp.tool() def calculate_bmi(height: float, weight: float) -> str: """计算BMI值并返回健康状态评估""" bmi = weight / (height * height) if bmi < 18.5: status = "偏瘦" elif bmi < 24: status = "正常" elif bmi < 28: status = "偏胖" else: status = "肥胖" return f"您的BMI值为: {bmi:.2f},健康状态: {status}"
if __name__ == "__main__": print("多功能助手启动...") try: mcp.run(transport="stdio") except Exception as e: print(f"多功能助手启动失败:{str(e)}")
|
JavaScript实现MCP服务器
对于Node.js开发者,以下是一个使用JavaScript实现的MCP服务器示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| const { MCPServer, MCPTools } = require('@mcp/server'); const fs = require('fs'); const path = require('path');
const tools = new MCPTools();
tools.register('calculate_bmi', (height, weight) => { const bmi = weight / (height * height); let status; if (bmi < 18.5) status = "偏瘦"; else if (bmi < 24) status = "正常"; else if (bmi < 28) status = "偏胖"; else status = "肥胖"; return `您的BMI值为: ${bmi.toFixed(2)},健康状态: ${status}`; });
tools.register('list_files', (directory) => { try { return fs.readdirSync(directory); } catch (error) { return [`目录访问错误: ${error.message}`]; } });
tools.register('get_weather', (city) => { const weatherData = { "北京": "晴朗,23°C", "上海": "多云,25°C", "广州": "小雨,28°C", "深圳": "晴朗,30°C" }; return `${city}的天气: ${weatherData[city] || '未知天气信息'}`; });
tools.register('convert_currency', (amount, fromCurrency, toCurrency) => { const rates = { "CNY": {"USD": 0.14, "EUR": 0.13, "JPY": 20.82}, "USD": {"CNY": 7.15, "EUR": 0.92, "JPY": 149.08}, "EUR": {"CNY": 7.80, "USD": 1.09, "JPY": 162.60}, "JPY": {"CNY": 0.048, "USD": 0.0067, "EUR": 0.0062} }; if (!rates[fromCurrency] || !rates[fromCurrency][toCurrency]) { return "不支持的货币转换"; } const converted = amount * rates[fromCurrency][toCurrency]; return `${amount} ${fromCurrency} = ${converted.toFixed(2)} ${toCurrency}`; });
const server = new MCPServer({ handleRequest: async (request) => { const { query } = request; let answer = `收到您的问题: ${query}\n\n`; answer += "我可以帮助您处理代码问题,您也可以使用以下工具函数:\n"; answer += "1. calculate_bmi - 计算BMI值\n"; answer += "2. list_files - 列出目录文件\n"; answer += "3. get_weather - 获取城市天气\n"; answer += "4. convert_currency - 货币转换\n"; return { answer, fileEdits: [], commands: [] }; }, tools, projectManaged: true, name: "多功能助手" });
server.start(3000).then(() => { console.log('MCP服务器已启动,监听端口3000...'); });
|
在Windows环境中使用MCP
Cursor中的MCP支持
Cursor是一款专为AI辅助编程设计的代码编辑器,它原生支持MCP协议。要在Cursor中使用MCP:
- 下载安装最新版的Cursor编辑器
- 打开一个项目文件夹
- 前往设置(Settings) -> MCP配置MCP服务器(全局)
- 或者在项目根目录下创建.cursor/mcp.json文件(局部)
- 添加全局MCP服务器或项目特定服务器
- 配置服务器命令,例如:
F:\Desktop\project\前端Test\mcp_project\mcp_project\venv\Scripts\python F:\Desktop\project\前端Test\mcp_project\mcp_project\main.py
- 在cursor设置中,如果绿灯亮起,表示配置成功

Cursor支持的MCP功能:
- 使用自定义工具函数(Tools)
- 分析项目结构
- 执行代码修改建议
- 提供基于项目上下文的智能建议
自定义MCP工具函数
当您在Cursor中设置MCP服务器后,可以看到它提供了多种工具函数,如:
calculate_bmi - 计算BMI指数
list_files - 列出目录文件
get_weather - 获取天气信息
convert_currency - 货币转换
您可以在AI对话框中直接调用这些工具,例如:
1
| 请使用calculate_bmi工具计算一个身高1.75m,体重70kg的人的BMI值
|
Cline中的MCP应用
Cline是Vscode中的一个命令行AI助手插件,也支持MCP协议:
- 安装Cline插件:
- 点击Cline插件图标,选择配置MCP服务器
- 可以直接把cursor中的mcp.json文件复制过来
- 绿灯亮起,表示配置成功
1
| 请使用list_files工具查看当前目录的文件
|
实际应用示例
使用MCP进行代码分析
场景:分析一个复杂项目的代码结构
对话示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| 用户: 分析这个项目的主要组件和它们之间的关系
AI: [分析项目结构...] 根据项目文件,我发现这是一个使用React和Node.js的全栈应用程序。
主要组件: 1. 前端 (React): - components/ 包含UI组件 - pages/ 包含路由页面 - services/ 包含API调用逻辑
2. 后端 (Node.js): - routes/ 定义API端点 - models/ 定义数据模型 - controllers/ 包含业务逻辑
组件间关系: - 前端通过services中的API调用与后端通信 - 后端controllers调用models进行数据操作 - [更多详细关系...]
|
使用工具函数
场景:在开发过程中使用MCP工具函数
对话示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| 用户: 我想知道当前项目中有哪些文件
AI: 我可以帮你查看。让我使用list_files工具:
[使用工具: list_files] 目录内容: - .git - .gitignore - .python-version - main.py - pyproject.toml - README.md
这个项目看起来是一个Python项目,包含一个主程序文件(main.py)和项目配置文件。
|
多文件修改建议
场景:需要在多个文件中实现一个新功能
对话示例:
1 2 3 4 5 6 7
| 用户: 我想添加一个新的API端点,用于用户个人资料更新
AI: 根据项目结构,我们需要修改以下文件:
1. 在routes/user.js中添加新路由: ```javascript router.put('/profile', authMiddleware, userController.updateProfile);
|
- 在controllers/user.js中添加处理函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| exports.updateProfile = async (req, res) => { try { const { name, bio, avatar } = req.body; const userId = req.user.id; const updatedUser = await User.findByIdAndUpdate( userId, { name, bio, avatar }, { new: true } ); res.status(200).json({ success: true, data: updatedUser }); } catch (error) { res.status(500).json({ success: false, message: error.message }); } };
|
- 在前端services/user.js中添加API调用:
1 2 3 4
| export const updateProfile = async (userData) => { const response = await api.put('/api/users/profile', userData); return response.data; };
|
您想要我实施这些更改吗?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| ## 高级MCP功能
### 文件系统感知能力
MCP服务器可以访问和理解完整的项目结构,这使得AI助手能够:
1. **全局搜索**:在整个项目中查找特定代码或模式 2. **理解依赖关系**:分析不同文件之间的导入和引用 3. **语义理解**:掌握代码的上下文和意图
实现文件系统感知的代码示例:
```python def get_file_structure(directory): """递归获取目录结构""" result = [] for item in os.listdir(directory): path = os.path.join(directory, item) if os.path.isdir(path): result.append({ "name": item, "type": "directory", "children": get_file_structure(path) }) else: result.append({ "name": item, "type": "file", "size": os.path.getsize(path) }) return result
|
上下文管理技术
高级MCP实现可以优化上下文传递,解决大型项目中上下文过大的问题:
- 智能筛选:只传递与当前任务相关的文件
- 滚动上下文:保持最新的对话和文件变更
- 压缩技术:使用摘要或引用减少上下文大小
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| function getRelevantFiles(query, allFiles) { const keywords = query.toLowerCase().split(' '); return allFiles.filter(file => { const relevance = keywords.some(keyword => file.path.toLowerCase().includes(keyword) || file.content.toLowerCase().includes(keyword) ); return relevance; }); }
|
自定义工具链
MCP协议的一个强大特性是能够创建自定义工具链,将多个工具函数组合使用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| def analyze_project_health(project_dir): """分析项目健康状况的工具链""" files = list_files(project_dir) complexity_report = analyze_complexity(project_dir) dependencies_report = check_dependencies(project_dir) return { "files_count": len(files), "complexity": complexity_report, "dependencies": dependencies_report, "health_score": calculate_health_score(complexity_report, dependencies_report) }
tools.register("project_health", analyze_project_health)
|
MCP协议的未来展望
发展趋势
- 工具集成:更多开发工具将原生支持MCP协议
- 标准化:MCP协议有望成为AI辅助编程的标准接口
- 功能扩展:支持更多类型的工具函数和复杂操作
- 性能优化:改进大型代码库的处理效率
- 多模态支持:扩展到处理图像、音频等非文本数据
社区贡献
MCP是一个开源协议,欢迎开发者通过以下方式参与贡献:
- 在GitHub仓库中提交问题或PR
- 开发支持MCP的工具和扩展
- 分享使用经验和最佳实践
- 参与协议改进的讨论
结语
MCP协议代表了AI辅助编程的一个重要进步,它使AI助手能够更好地理解和操作代码库,从而提供更准确、更有用的建议。通过本文的介绍,相信大家已经对MCP协议有了基本的了解,并能够开始在自己的项目中尝试使用MCP。
无论是使用现有的支持MCP的工具,还是开发自己的MCP应用,这一协议都将显著提升AI辅助开发的效率和体验。随着更多开发者和工具加入MCP生态系统,我们可以期待AI辅助编程的体验会变得越来越流畅、智能和高效。
参考资料
- Model Context Protocol官方文档
- MCP GitHub仓库
- Cursor编辑器
- Cline命令行AI助手
- Cloud Studio MCP协议课程