Spring AI实现MCP(Model Context Protocol)详解与实践
一、什么是MCP?
MCP(Model Context Protocol)是一个用于AI模型与外部系统交互的协议标准。它允许AI模型通过标准化的接口访问外部数据源、工具和服务,从而扩展模型的能力边界。
MCP的核心特点
- 标准化协议:提供统一的接口规范,便于不同系统之间的集成
- 上下文管理:能够动态获取和管理上下文信息
- 工具调用:支持模型调用外部工具和服务
- 可扩展性:易于添加新的数据源和功能
MCP的应用场景
- 数据库查询和操作
- API服务调用
- 文件系统访问
- 实时数据获取
- 业务系统集成
二、Spring AI中的MCP支持
Spring AI是Spring生态系统中的AI集成框架,提供了对MCP的原生支持。通过Spring AI,我们可以轻松地将MCP协议集成到Spring应用中。
Spring AI MCP的核心组件
- MCP Client:用于连接MCP服务器
- MCP Tools:定义可用的工具和操作
- Context Provider:提供上下文信息
- 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的优势
- 标准化:统一的协议规范,降低集成复杂度
- 灵活性:支持多种传输方式(stdio、http等)
- 可扩展:易于添加新的工具和功能
- 类型安全:通过注解定义工具,提供类型检查
- Spring集成:与Spring生态系统无缝集成
六、总结
通过Spring AI实现MCP,我们可以:
- 轻松地将AI模型与外部系统集成
- 提供标准化的工具调用接口
- 实现动态上下文管理
- 扩展AI模型的能力边界
MCP为AI应用提供了一个强大的扩展机制,使得AI模型能够访问和操作外部资源,从而提供更智能、更实用的服务。