AI - MCP(Model Context Protocol,模型上下文协议)
一、基础定义
MCP(Model Context Protocol,模型上下文协议)
MCP = 模型上下文协议,Anthropic(Claude 出品方)2024.11 开源的开放通用通信标准,业内称作AI 领域/应用的 USB-C 通用标准接口,用来统一大模型 (LLM) 和外部数据 / 工具的对接规范。
MCP由Anthropic在2024年11月推出的开源开放协议,被称为AI 领域/应用的USB-C通用标准接口。它的核心作用是为大语言模型连接外部工具、数据源和服务提供统一的标准化接口,解决了过去每个AI模型对接不同工具都需要单独开发定制接口的效率问题,简化了AI智能体的开发和扩展。
它采用客户端-服务器架构,支持同时对接本地资源(数据库、本地文件)和远程服务(GitHub、Slack等API),目前已经有上千个社区服务器和集成应用落地,OpenAI、百度智能云、支付宝等国内外厂商都已经支持该协议。
MCP 服务器聚合网站:https://mcp.so/
mcp.so:AI 领域的 MCP 协议应用商店,全球最大 MCP 服务器聚合网站,用来给 Claude、Cursor 等 AI 工具外挂扩展能力。
二、核心作用:解决 N×M 对接痛点
无 MCP 时:N 个大模型 × M 个工具 = N×M 套定制接口,每个对接都要单独开发,成本极高;
有 MCP 后:模型端实现 1 次 MCP 客户端、工具端实现 1 次 MCP 服务端,即可全生态互通(N+M),实现 AI 工具即插即用。
AI 领域/应用的USB-C通用标准接口:简单说就是给大模型装了一个"万能接口",让 AI 能连接外部数据和工具,就像 USB-C 接口能让电脑连接各种设备一样 。
三、工作原理
1、工作原理:采用客户端 - 服务器架构
三层标准架构(C/S 架构,基于 JSON-RPC2.0)
- MCP Host(主机):搭载大模型的应用,如 Claude 桌面端、Cursor 编辑器、自研 AI Agent;管控用户授权、权限。
- MCP Client(客户端):Host 内部连接器,和 MCP Server 建立会话、收发标准化指令。
- MCP Server(服务端):对接真实资源,对外暴露三类能力:
- Resources(资源):只读数据(本地文件、数据库、接口返回数据,给模型做上下文)
- Tools(工具):可执行函数(查天气、读写文件、调用接口、运行代码)
- Prompts(提示词):预制提示词模板,复用工作流
2、两种通信传输方式
- 本地进程通信:
stdio(标准输入输出),IDE、本地文件 AI 常用,低延迟; - 远程网络通信:Streamable HTTP/WebSocket,跨服务器、云端系统对接。
四、三大核心优势
- 标准化降本:一套协议对接全量数据源,大幅减少重复开发;
- 高安全性:资源逻辑全在 MCP Server,密钥不传给大模型,细粒度权限 + 全操作审计;
- 生态通用:OpenAI、Google、国内云厂商全兼容,现成 MCP 服务:文件、MySQL、Notion、Git、搜索引擎等开箱即用。
五、落地使用场景
- AI 编程 IDE:Cursor 通过 MCP 直接读写项目文件、调用终端;
- 企业知识库:大模型通过 MCP 连内部数据库、文档系统,做私有 RAG;
- AI 智能体 Agent:自动查实时行情、机票、企业 CRM 数据,突破模型训练数据截止限制、减少幻觉。
六、和 Function Calling、RAG 区别
- RAG:查资料、补静态知识(只读、给上下文)
- Function Calling:模型侧私有规则,仅单模型调用少量函数,绑定模型;
- MCP:跨厂商开放协议,独立于大模型,一套服务全模型通用,支持海量异构数据源。
| 维度 | RAG(检索增强生成) | Function Call(函数调用) | MCP (Model Context Protocol,模型上下文协议) |
|---|---|---|---|
| 本质属性 | 技术方案 / 架构范式(检索 + 生成) | 大模型内置原生能力(模型输出规范) | 开放通信协议 (JSON-RPC)、通用标准接口 |
| 核心目的 | 从知识库拉取静态文档数据塞进 Prompt,解决幻觉、知识滞后 | 让 LLM 自主生成入参,调用本地 / 远端自定义函数,获取实时数据 | 统一 LLM 和外部服务通信标准,一次开发全模型 / 全客户端复用工具 |
| 数据流向 | 单向只读:知识库→向量检索→上下文→LLM(只能拿数据,不能改业务数据) | 单次短回合:LLM 出参→应用层执行函数→结果回灌 LLM | 双向读写 + 长连接:客户端 (LLM)↔MCP 服务 (DB / 文件 / API),可增删改查、动态注册工具 |
| 通俗比喻 | 开卷查参考书(写答案前翻资料) | 随身小纸条,呼叫手边工具 | AI 通用 USB 接口,即插即用各类外设服务 |
七、Java中应用
1. pom.xml(所有必需依赖)
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>3.2.0</version> </parent> <groupId>com.example</groupId> <artifactId>springboot-mcp</artifactId> <version>0.0.1</version> <dependencies> <!-- SpringBoot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!-- MCP 官方SDK --> <dependency> <groupId>com.anthropic</groupId> <artifactId>mcp-sdk</artifactId> <version>1.0.0</version> </dependency> <!-- MySQL --> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <scope>runtime</scope> </dependency> <!-- Redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- 工具类 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson2</artifactId> <version>2.0.32</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>2. application.yml(配置)
spring: datasource: url: jdbc:mysql://localhost:3306/test username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver data: redis: host: localhost port: 6379 server: port: 80803. 主程序(SpringBoot + MCP 全功能)
SpringBootMcpApplication.java
import com.anthropic.mcp.server.McpServer; import com.anthropic.mcp.server.Tool; import com.alibaba.fastjson2.JSON; import jakarta.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.Map; @SpringBootApplication public class SpringBootMcpApplication { public static void main(String[] args) { SpringApplication.run(SpringBootMcpApplication.class, args); } } // 演示Service(可注入任何Bean) @Service class DemoService { public String hello(String name) { return "SpringBoot服务返回:你好," + name; } } // MCP 核心服务 @Component class FullMcpServer { @Autowired private DemoService demoService; @Autowired private JdbcTemplate jdbcTemplate; @Autowired private StringRedisTemplate redisTemplate; @PostConstruct public void start() { McpServer server = new McpServer(); // ===== 1. 调用SpringBoot服务 ===== server.registerTool(Tool.builder() .name("callSpringService") .description("调用SpringBoot服务") .inputSchema(""" {"type":"object","properties":{"name":{"type":"string"}},"required":["name"]}""") .handler(p -> demoService.hello(p.get("name").getAsString())) .build() ); // ===== 2. 执行SQL ===== server.registerTool(Tool.builder() .name("queryDB") .description("执行SQL查询") .inputSchema(""" {"type":"object","properties":{"sql":{"type":"string"}},"required":["sql"]}""") .handler(p -> { List<Map<String, Object>> list = jdbcTemplate.queryForList(p.get("sql").getAsString()); return JSON.toJSONString(list); }) .build() ); // ===== 3. Redis操作 ===== server.registerTool(Tool.builder() .name("setRedis") .description("设置Redis") .inputSchema(""" {"type":"object","properties":{"k":{"type":"string"},"v":{"type":"string"}},"required":["k","v"]}""") .handler(p -> { redisTemplate.opsForValue().set(p.get("k").getAsString(), p.get("v").getAsString()); return "Redis设置成功"; }) .build() ); // ===== 4. 读取文件 ===== server.registerTool(Tool.builder() .name("readFile") .description("读取文件") .inputSchema(""" {"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}""") .handler(p -> Files.readString(Paths.get(p.get("path").getAsString()))) .build() ); // ===== 5. 执行系统命令 ===== server.registerTool(Tool.builder() .name("runCmd") .description("执行命令") .inputSchema(""" {"type":"object","properties":{"cmd":{"type":"string"}},"required":["cmd"]}""") .handler(p -> { Process process = new ProcessBuilder( System.getProperty("os.name").toLowerCase().contains("win") ? new String[]{"cmd", "/c", p.get("cmd").getAsString()} : new String[]{"sh", "-c", p.get("cmd").getAsString()} ).redirectErrorStream(true).start(); return new String(process.getInputStream().readAllBytes()); }) .build() ); new Thread(server::startStdio).start(); System.out.println("✅ SpringBoot MCP 服务已启动(全功能版)"); } }4. 接入 Cursor(直接用)
打开 Cursor 设置 → MCP
json
{ "mcpServers": { "springboot-full": { "command": "java", "args": ["-jar", "target/springboot-mcp-0.0.1.jar"] } } }5. 你可以直接对 AI 说:
- 帮我调用 Spring 服务,名字是张小明
- 帮我查询数据库:select * from user
- 帮我设置 Redis:key=name value = 李四
- 帮我读文件:application.yml
- 帮我执行命令:dir /ifconfig
