第三章:5、MCP协议入门

22 阅读1分钟

1. 理解MCP的核心价值

  • MCP 是一个标准化协议,使AI应用能够以统一的方式接入各种外部工具和数据源。
  • 类比说明:如同 JDBC 让 Java 用统一接口访问不同数据库,MCP 让 AI 用统一接口调用不同工具服务。
  • 你可以将自己的工具暴露为 MCP Server,也可以消费他人提供的 MCP Server 工具。

2. 配置MCP Client

步骤如下:

(1) 在 pom.xml 中添加MCP依赖:

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-mcp-client</artifactId>
</dependency>

(2) 在 application.yml 中配置MCP Server连接:

spring:
  ai:
    mcp:
      client:
        stdio:
          connections:
            # 接入一个示例MCP Server(文件系统操作)
            filesystem:
              # 本地有安装node的话,这里只是为了测试。
              # 直接用node运行本地安装的包,避免npx下载延迟和额外输出干扰stdio握手
              command: D:\nodejs\node.exe
              args:
                - "D:/IdeaProject/ai-study/node_modules/@modelcontextprotocol/server-filesystem/dist/index.js"
                - "D:/IdeaProject/ai-study"

3. 混合使用本地工具和MCP工具

使用示例:

  • 注入 MCP 工具:
@Resource
private SyncMcpToolCallbackProvider mcpTools;
  • 配置 ChatClient,支持本地工具与MCP工具混用:
@Bean("mcpAgentChatClient")
public ChatClient mcpAgentChatClient(ChatClient.Builder builder, OpsTools opsTools) {
    return builder
            .defaultSystem("你是一个智能运维助手,可以查询服务状态,也可以读写文件。")
            .defaultTools(opsTools, mcpTools)  // 本地工具 + MCP工具混用
            .build();
}
  • 定义接口,进行AI对话:
@GetMapping(value = "/mcp/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> mcpChat(@RequestParam String message,
                            @RequestParam(defaultValue = "default") String conversationId) {
    return mcpChatClient.prompt()
            .user(message)
            .advisors(spec -> spec.param(ChatMemory.CONVERSATION_ID, conversationId))
            .stream()
            .content();
}

4. 测试

curl "http://localhost:8080/agent/mcp/chat?message=帮我查看/tmp目录下的文件列表"