首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >longchain4j 学习系列(4)-mcp调用

longchain4j 学习系列(4)-mcp调用

作者头像
菩提树下的杨过
发布2025-11-25 08:38:18
发布2025-11-25 08:38:18
50
举报

继续学习langchain4j,以下是langchain4j 调用MCP的示例:

1、添加pom依赖

代码语言:javascript
复制
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初始化

代码语言:javascript
复制
/**
 * 初始化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接口

代码语言:javascript
复制
    private interface Assistant {
        String chat(String userMessage);
    }

4、调用MCP

代码语言:javascript
复制
    /**
     * 直接获取订单状态信息
     *
     * @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)

image
image

日志:

代码语言:javascript
复制
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" ]
      }
    }
  } ]
}

文中代码:GitHub - yjmyzz/langchain4j-study at day04

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-11-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档