Spring AI实现MCP(Model Context Protocol)详解与实践

Spring AI实现MCP(Model Context Protocol)详解与实践

一、什么是MCP?

MCP(Model Context Protocol)是一个用于AI模型与外部系统交互的协议标准。它允许AI模型通过标准化的接口访问外部数据源、工具和服务,从而扩展模型的能力边界。

MCP的核心特点

  1. 标准化协议:提供统一的接口规范,便于不同系统之间的集成
  2. 上下文管理:能够动态获取和管理上下文信息
  3. 工具调用:支持模型调用外部工具和服务
  4. 可扩展性:易于添加新的数据源和功能

MCP的应用场景

  • 数据库查询和操作
  • API服务调用
  • 文件系统访问
  • 实时数据获取
  • 业务系统集成

二、Spring AI中的MCP支持

Spring AI是Spring生态系统中的AI集成框架,提供了对MCP的原生支持。通过Spring AI,我们可以轻松地将MCP协议集成到Spring应用中。

Spring AI MCP的核心组件

  1. MCP Client:用于连接MCP服务器
  2. MCP Tools:定义可用的工具和操作
  3. Context Provider:提供上下文信息
  4. Message Handler:处理MCP消息

三、Spring AI实现MCP的步骤

1. 添加依赖

首先,在pom.xml中添加Spring AI相关依赖:

xml 复制代码
<dependencies>
    <!-- Spring AI Core -->
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-core</artifactId>
        <version>1.0.0</version>
    </dependency>
    
    <!-- Spring AI MCP -->
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-mcp</artifactId>
        <version>1.0.0</version>
    </dependency>
    
    <!-- Spring Boot Starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

2. 配置MCP连接

application.yml中配置MCP服务器连接:

yaml 复制代码
spring:
  ai:
    mcp:
      enabled: true
      servers:
        - name: database-mcp
          transport: stdio
          command: node
          args:
            - /path/to/mcp-server.js
        - name: api-mcp
          transport: http
          url: http://localhost:8080/mcp
          api-key: ${MCP_API_KEY}

3. 创建MCP工具接口

定义MCP工具接口:

java 复制代码
package com.example.mcp.tools;

import org.springframework.ai.mcp.spec.Tool;
import org.springframework.stereotype.Component;

@Component
public class DatabaseQueryTool {
    
    @Tool(
        name = "query_database",
        description = "查询数据库中的信息"
    )
    public String queryDatabase(
        @Tool.Param(name = "sql", description = "SQL查询语句") String sql,
        @Tool.Param(name = "table", description = "表名") String table
    ) {
        // 实现数据库查询逻辑
        return executeQuery(sql, table);
    }
    
    private String executeQuery(String sql, String table) {
        // 实际的数据库查询实现
        // ...
        return "查询结果";
    }
}

4. 实现MCP客户端

创建MCP客户端来连接和交互:

java 复制代码
package com.example.mcp.client;

import org.springframework.ai.mcp.McpClient;
import org.springframework.ai.mcp.McpMessage;
import org.springframework.ai.mcp.McpRequest;
import org.springframework.ai.mcp.McpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class McpService {
    
    @Autowired
    private McpClient mcpClient;
    
    /**
     * 发送MCP请求并获取响应
     */
    public String sendRequest(String toolName, Object... params) {
        McpRequest request = McpRequest.builder()
            .tool(toolName)
            .parameters(params)
            .build();
            
        McpResponse response = mcpClient.send(request);
        return response.getContent();
    }
    
    /**
     * 获取上下文信息
     */
    public String getContext(String contextId) {
        McpMessage message = McpMessage.builder()
            .type("get_context")
            .contextId(contextId)
            .build();
            
        McpResponse response = mcpClient.send(message);
        return response.getContent();
    }
}

5. 创建控制器

创建REST控制器来暴露MCP功能:

java 复制代码
package com.example.mcp.controller;

import com.example.mcp.client.McpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/mcp")
public class McpController {
    
    @Autowired
    private McpService mcpService;
    
    @PostMapping("/query")
    public String query(@RequestBody QueryRequest request) {
        return mcpService.sendRequest(
            "query_database",
            request.getSql(),
            request.getTable()
        );
    }
    
    @GetMapping("/context/{contextId}")
    public String getContext(@PathVariable String contextId) {
        return mcpService.getContext(contextId);
    }
}

四、MCP实现示例:数据库查询工具

下面是一个完整的MCP实现示例,展示如何创建一个数据库查询工具。

1. 数据库查询工具实现

java 复制代码
package com.example.mcp.tools;

import org.springframework.ai.mcp.spec.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class DatabaseQueryTool {
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Tool(
        name = "query_user_info",
        description = "根据用户ID查询用户信息"
    )
    public String queryUserInfo(
        @Tool.Param(name = "userId", description = "用户ID") Long userId
    ) {
        String sql = "SELECT id, name, email, phone FROM users WHERE id = ?";
        List<Map<String, Object>> results = jdbcTemplate.queryForList(sql, userId);
        
        if (results.isEmpty()) {
            return "未找到用户信息";
        }
        
        Map<String, Object> user = results.get(0);
        return String.format(
            "用户信息:ID=%s, 姓名=%s, 邮箱=%s, 电话=%s",
            user.get("id"),
            user.get("name"),
            user.get("email"),
            user.get("phone")
        );
    }
    
    @Tool(
        name = "query_order_list",
        description = "查询用户的订单列表"
    )
    public String queryOrderList(
        @Tool.Param(name = "userId", description = "用户ID") Long userId,
        @Tool.Param(name = "limit", description = "返回记录数限制") Integer limit
    ) {
        String sql = "SELECT id, order_no, amount, status, create_time " +
                     "FROM orders WHERE user_id = ? ORDER BY create_time DESC LIMIT ?";
        List<Map<String, Object>> orders = jdbcTemplate.queryForList(sql, userId, limit);
        
        if (orders.isEmpty()) {
            return "该用户暂无订单";
        }
        
        StringBuilder result = new StringBuilder("订单列表:\n");
        for (Map<String, Object> order : orders) {
            result.append(String.format(
                "订单号:%s, 金额:%s, 状态:%s, 创建时间:%s\n",
                order.get("order_no"),
                order.get("amount"),
                order.get("status"),
                order.get("create_time")
            ));
        }
        
        return result.toString();
    }
}

2. MCP服务集成

java 复制代码
package com.example.mcp.service;

import org.springframework.ai.mcp.McpClient;
import org.springframework.ai.mcp.McpRequest;
import org.springframework.ai.mcp.McpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DatabaseMcpService {
    
    @Autowired
    private McpClient mcpClient;
    
    /**
     * 查询用户信息
     */
    public String getUserInfo(Long userId) {
        McpRequest request = McpRequest.builder()
            .tool("query_user_info")
            .parameter("userId", userId)
            .build();
            
        McpResponse response = mcpClient.send(request);
        return response.getContent();
    }
    
    /**
     * 查询订单列表
     */
    public String getOrderList(Long userId, Integer limit) {
        McpRequest request = McpRequest.builder()
            .tool("query_order_list")
            .parameter("userId", userId)
            .parameter("limit", limit)
            .build();
            
        McpResponse response = mcpClient.send(request);
        return response.getContent();
    }
}

3. 使用示例

java 复制代码
package com.example.mcp.example;

import com.example.mcp.service.DatabaseMcpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class McpExample implements CommandLineRunner {
    
    @Autowired
    private DatabaseMcpService databaseMcpService;
    
    @Override
    public void run(String... args) {
        // 查询用户信息
        String userInfo = databaseMcpService.getUserInfo(1L);
        System.out.println(userInfo);
        
        // 查询订单列表
        String orderList = databaseMcpService.getOrderList(1L, 10);
        System.out.println(orderList);
    }
}

五、MCP的优势

  1. 标准化:统一的协议规范,降低集成复杂度
  2. 灵活性:支持多种传输方式(stdio、http等)
  3. 可扩展:易于添加新的工具和功能
  4. 类型安全:通过注解定义工具,提供类型检查
  5. Spring集成:与Spring生态系统无缝集成

六、总结

通过Spring AI实现MCP,我们可以:

  • 轻松地将AI模型与外部系统集成
  • 提供标准化的工具调用接口
  • 实现动态上下文管理
  • 扩展AI模型的能力边界

MCP为AI应用提供了一个强大的扩展机制,使得AI模型能够访问和操作外部资源,从而提供更智能、更实用的服务。

参考资料

相关推荐
秋刀鱼 ..2 小时前
第七届国际科技创新学术交流大会暨机械工程与自动化国际学术会议(MEA 2025)
运维·人工智能·python·科技·机器人·自动化
汝生淮南吾在北5 小时前
SpringBoot+Vue饭店点餐管理系统
java·vue.js·spring boot·毕业设计·毕设
冬夜戏雪8 小时前
【java学习日记】【2025.12.7】【7/60】
java·开发语言·学习
CC.GG8 小时前
【C++】二叉搜索树
java·c++·redis
学历真的很重要8 小时前
VsCode+Roo Code+Gemini 2.5 Pro+Gemini Balance AI辅助编程环境搭建(理论上通过多个Api Key负载均衡达到无限免费Gemini 2.5 Pro)
前端·人工智能·vscode·后端·语言模型·负载均衡·ai编程
普通网友8 小时前
微服务注册中心与负载均衡实战精要,微软 2025 年 8 月更新:对固态硬盘与电脑功能有哪些潜在的影响。
人工智能·ai智能体·技术问答
苍何8 小时前
一人手搓!AI 漫剧从0到1详细教程
人工智能
地瓜伯伯9 小时前
Nginx终极配置指南:负载均衡、限流、反向代理、IP白名单、SSL、云原生、DNS解析、缓存加速全都有
spring boot·nginx·spring·spring cloud·微服务·云原生·负载均衡
苍何9 小时前
Gemini 3 刚刷屏,蚂蚁灵光又整活:一句话生成「闪游戏」
人工智能