← 返回首页 📚 实战课程
📑 本篇章节导航 (共5章,点击直达)
本节目标核心知识面试模拟动手练习下一课预告

P3-06 - MCP协议实战

本节目标

1. MCP协议解决什么问题?和Function Calling有什么区别?

2. MCP的Client-Server架构是怎样的?

3. 怎么用Java实现一个MCP Server?

4. 怎么把MCP Server集成到Spring AI?

5. MCP的生态和工具市场概念?

核心知识

一、MCP是什么 — 用通俗的话解释


MCP = Model Context Protocol(模型上下文协议)
由Anthropic(Claude的开发商)提出,2024年底发布

解决的问题:
  每个大模型应用要接入不同的数据源和工具,都要写一遍集成代码。
  换一个模型,又要重写一遍。

类比:
  MCP 之于 AI应用,相当于 JDBC 之于 数据库
  或者 USB 之于 外设

有了MCP:
  AI应用(Client) ← MCP标准协议 → MCP Server(提供工具和数据)
  一个MCP Server可以被任何支持MCP的AI应用使用

Function Calling vs MCP:
  Function Calling:应用内嵌工具定义,工具和应用紧耦合
  MCP:工具独立部署,通过标准协议暴露,应用和工具解耦

  Function Calling = 自己家里装了个工具箱
  MCP = 有一个标准化的工具市场,按需取用

二、MCP架构


┌─────────────────────────────────────┐
│           AI应用(Host)              │
│  如:Claude Desktop / 你的Spring应用  │
│                                      │
│  ┌────────────────────────────────┐ │
│  │      MCP Client(客户端)       │ │
│  │  负责与MCP Server通信           │ │
│  └───────────┬────────────────────┘ │
│              │                      │
│     ┌────────┼────────┐            │
│     ▼        ▼        ▼            │
│  ┌─────┐ ┌─────┐ ┌─────┐          │
│  │本地  │ │远程  │ │远程  │          │
│  │Server│ │Server│ │Server│          │
│  │文件系统│ │数据库│ │天气API│         │
│  └─────┘ └─────┘ └─────┘          │
└─────────────────────────────────────┘

MCP通信方式:
1. stdio(标准输入输出)— 本地Server,进程间通信
2. SSE(Server-Sent Events)— 远程Server,HTTP通信

MCP定义的能力类型:
- Tools:可调用的函数(查询、执行操作)
- Resources:可读取的数据源(文件、数据库记录)
- Prompts:预定义的Prompt模板

三、手写MCP Server(Java)


// 使用Spring AI的MCP Server支持
// 依赖:spring-ai-mcp-server-spring-boot-starter

@Configuration
public class McpServerConfig {

    @Bean
    public McpServer mcpServer() {
        return McpServer.builder()
            .name("flight-pricing-tools")
            .version("1.0.0")
            .tool(Tool.builder()
                .name("queryFlightPrice")
                .description("查询指定航线的航班价格")
                .inputSchema("""
                    {
                      "type": "object",
                      "properties": {
                        "departure": {"type": "string", "description": "出发城市三字码"},
                        "arrival": {"type": "string", "description": "到达城市三字码"},
                        "date": {"type": "string", "description": "日期 yyyy-MM-dd"}
                      },
                      "required": ["departure", "arrival", "date"]
                    }
                    """)
                .handler(this::handleQueryPrice)
                .build())
            .tool(Tool.builder()
                .name("adjustFlightPrice")
                .description("调整指定航线的价格")
                .inputSchema("""
                    {
                      "type": "object",
                      "properties": {
                        "routeId": {"type": "string"},
                        "newPrice": {"type": "number"},
                        "reason": {"type": "string"}
                      },
                      "required": ["routeId", "newPrice"]
                    }
                    """)
                .handler(this::handleAdjustPrice)
                .build())
            .build();
    }

    private ToolResult handleQueryPrice(Map<String, Object> args) {
        String departure = (String) args.get("departure");
        String arrival = (String) args.get("arrival");
        String date = (String) args.get("date");
        // 调用实际查询逻辑
        String result = priceService.queryPrice(departure, arrival, date);
        return ToolResult.success(result);
    }

    private ToolResult handleAdjustPrice(Map<String, Object> args) {
        String routeId = (String) args.get("routeId");
        double newPrice = ((Number) args.get("newPrice")).doubleValue();
        priceService.adjustPrice(routeId, newPrice);
        return ToolResult.success("价格调整成功");
    }
}

四、Spring AI集成MCP Client


// 在AI应用中使用MCP Client调用外部工具

@Configuration
public class McpClientConfig {

    @Bean
    public McpClient mcpClient() {
        // 连接远程MCP Server
        return McpClient.builder()
            .transport(McpTransport.sse("http://localhost:8081/mcp"))
            .build();
    }
}

@Service
public class McpAgentService {

    private final ChatClient chatClient;

    public McpAgentService(ChatModel chatModel, McpClient mcpClient) {
        // 从MCP Server获取工具列表,注册到ChatClient
        List<FunctionCallback> mcpTools = mcpClient.listTools().stream()
            .map(tool -> FunctionCallback.builder()
                .function(tool.getName(), (input) -> {
                    return mcpClient.callTool(tool.getName(), input);
                })
                .description(tool.getDescription())
                .inputType(tool.getInputSchema())
                .build())
            .collect(Collectors.toList());

        this.chatClient = ChatClient.builder(chatModel)
            .defaultAdvisors(new SimpleLoggerAdvisor())
            .defaultFunctions(mcpTools.toArray(new FunctionCallback[0]))
            .build();
    }

    public String chat(String question) {
        return chatClient.prompt()
            .user(question)
            .call()
            .content();
    }
}

五、MCP生态和工具市场


MCP的意义不只是协议,而是生态:

已有MCP Server(持续增长中):
- @anthropic/filesystem — 文件系统读写
- @anthropic/github — GitHub操作
- @anthropic/postgres — PostgreSQL查询
- @anthropic/brave-search — 网络搜索
- 社区贡献:Slack、Notion、Google Drive、Jira...

类比:
  MCP = AI应用的"App Store"
  每个MCP Server = 一个App
  AI应用 = 手机

对Java开发者的机会:
  1. 给公司内部系统写MCP Server(让AI能调用公司API)
  2. 给常用中间件写MCP Server(Redis、MySQL、ES等)
  3. 这本身就是一个有价值的技能点(面试加分)

面试模拟

Q1: "MCP和Function Calling有什么区别?你们用的哪个?"

"Function Calling是模型能力——让模型知道有哪些工具可以调用。
MCP是连接协议——定义了工具怎么暴露、怎么发现、怎么调用。

>

打个比方:Function Calling规定了'模型能点菜',
MCP规定了'菜单怎么展示、厨房怎么接收订单'。

>

我们现在用Function Calling,工具直接在代码里注册。
后续计划把工具抽成MCP Server,这样不同的AI应用可以复用同一套工具,
不用每个应用都写一遍工具注册代码。

>

Spring AI已经支持MCP,迁移成本不高。"

Q2: "MCP Server的安全性怎么保障?"

"三个层面:
1. 传输安全:远程MCP Server走HTTPS + Token认证
2. 权限控制:MCP Server内部做细粒度权限检查(哪些工具允许调用)
3. 审计日志:所有MCP调用都记录(谁调的、调了什么、参数是什么)

>

特别是修改类工具(调价、下单),必须有审批机制——
MCP Server返回建议,人类确认后才真正执行。"

动手练习

练习1:实现一个MCP Server

1. 创建Spring Boot项目

2. 定义2-3个Tool(查询数据库、查询API)

3. 启动MCP Server

4. 用MCP Client连接测试

练习2:集成MCP到ChatClient

1. 在主应用中添加MCP Client

2. 动态加载MCP Server的工具

3. 测试对话中自动调用MCP工具

下一课预告

P3-07将深入AI生产化:Prompt版本管理、Token成本控制、限流降级、监控告警。