继续学习langchain4j,以下是langchain4j 调用MCP的示例:
1、添加pom依赖
1 <dependency>
2 <groupId>dev.langchain4j</groupId>
3 <artifactId>langchain4j-mcp</artifactId>
4 <version>1.1.0-beta7</version>
5 </dependency>这里要注意版本号,不同的版本api细节略有不同。
2、Mcp Client初始化
/**
* 初始化SSE客户端
*
* @param sseUrl SSE服务器连接地址
* @return McpClient实例
*/
private static McpClient initSseClient(String sseUrl) {
// 构建默认MCP客户端
return new DefaultMcpClient.Builder()
.clientName("yjmyzz.cnblogs.com")
.protocolVersion("2024-11-05")
.toolExecutionTimeout(Duration.ofSeconds(10))
// 配置HTTP传输层参数
.transport(new HttpMcpTransport.Builder()
// 设置SSE服务器连接URL
.sseUrl(sseUrl)
// 设置连接超时时间
.timeout(Duration.ofSeconds(10))
// 启用请求日志记录
.logRequests(true)
// 启用响应日志记录
.logResponses(true)
.build())
.build();
}3、定义1个Assistant接口
private interface Assistant {
String chat(String userMessage);
}4、调用MCP
/**
* 直接获取订单状态信息
*
* @param orderId 订单ID,用于查询指定订单的状态
* @return ResponseEntity<String> 包含订单状态信息的响应实体,成功时返回订单状态JSON字符串,
* 失败时返回包含错误信息的JSON字符串
*/
@GetMapping(value = "/order", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> getOrderStatusDirect(@RequestParam String orderId) {
McpClient mcpClient = null;
try {
// 初始化SSE客户端连接
mcpClient = initSseClient("http://localhost:8070/sse");
// 构建AI助手服务,配置聊天模型和工具提供者
Assistant assistant = AiServices.builder(Assistant.class)
.chatModel(deepSeekChatModel)
.toolProvider(McpToolProvider.builder().mcpClients(mcpClient).build())
.build();
// 调用AI助手查询订单状态
String response = assistant.chat("查询订单状态,订单号:" + orderId);
return ResponseEntity.ok(response);
} catch (Exception e) {
log.error("查询订单状态时发生错误", e);
return ResponseEntity.ok("{\"error\":\"查询订单状态失败: " + e.getMessage() + "\"}");
} finally {
// 确保MCP客户端连接被正确关闭
if (mcpClient != null) {
try {
mcpClient.close();
} catch (Exception e) {
log.error("关闭MCP客户端时发生错误", e);
}
}
}
}注:这里的mcp server 可参考 spring-ai 学习系列(5)-MCP(webflux sse)

日志:
2025-10-03T20:30:43.277+08:00 INFO 18312 --- [longchain4j-study] [nio-8080-exec-2] d.l.http.client.log.LoggingHttpClient : HTTP request:
- method: POST
- url: https://api.deepseek.com/chat/completions
- headers: [Authorization: Beare...00], [User-Agent: langchain4j-openai], [Content-Type: application/json]
- body: {
"model" : "deepseek-chat",
"messages" : [ {
"role" : "user",
"content" : "查询订单状态,订单号:25070602"
} ],
"temperature" : 0.7,
"stream" : false,
"max_tokens" : 2048,
"tools" : [ {
"type" : "function",
"function" : {
"name" : "queryOrderStatus",
"description" : "根据订单号查询订单状态",
"parameters" : {
"type" : "object",
"properties" : {
"orderNo" : {
"type" : "string",
"description" : "订单号,格式为8位数字,比如:25070601"
}
},
"required" : [ "orderNo" ]
}
}
} ]
}
...
2025-10-03T20:30:45.770+08:00 INFO 18312 --- [longchain4j-study] [nio-8080-exec-2] d.l.http.client.log.LoggingHttpClient : HTTP request:
- method: POST
- url: https://api.deepseek.com/chat/completions
- headers: [Authorization: Beare...00], [User-Agent: langchain4j-openai], [Content-Type: application/json]
- body: {
"model" : "deepseek-chat",
"messages" : [ {
"role" : "user",
"content" : "查询订单状态,订单号:25070602"
}, {
"role" : "assistant",
"content" : "我来帮您查询订单号为25070602的订单状态。",
"tool_calls" : [ {
"id" : "call_00_QnwEmctjY5kaQf5MEQ5C2i9Y",
"type" : "function",
"function" : {
"name" : "queryOrderStatus",
"arguments" : "{\"orderNo\": \"25070602\"}"
}
} ]
}, {
"role" : "tool",
"tool_call_id" : "call_00_QnwEmctjY5kaQf5MEQ5C2i9Y",
"content" : "\"订单号:25070602,订单状态:已完成\""
} ],
"temperature" : 0.7,
"stream" : false,
"max_tokens" : 2048,
"tools" : [ {
"type" : "function",
"function" : {
"name" : "queryOrderStatus",
"description" : "根据订单号查询订单状态",
"parameters" : {
"type" : "object",
"properties" : {
"orderNo" : {
"type" : "string",
"description" : "订单号,格式为8位数字,比如:25070601"
}
},
"required" : [ "orderNo" ]
}
}
} ]
}