|
| 1 | +/* |
| 2 | + * Copyright 2024-2025 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.alibaba.cloud.ai.graph.node; |
| 18 | + |
| 19 | +import com.alibaba.cloud.ai.graph.OverAllState; |
| 20 | +import com.alibaba.cloud.ai.graph.action.NodeAction; |
| 21 | +import io.modelcontextprotocol.client.McpClient; |
| 22 | +import io.modelcontextprotocol.client.McpSyncClient; |
| 23 | +import io.modelcontextprotocol.client.transport.HttpClientSseClientTransport; |
| 24 | +import io.modelcontextprotocol.spec.McpSchema; |
| 25 | +import io.modelcontextprotocol.spec.McpSchema.CallToolResult; |
| 26 | +import io.modelcontextprotocol.spec.McpSchema.TextContent; |
| 27 | +import org.slf4j.Logger; |
| 28 | +import org.slf4j.LoggerFactory; |
| 29 | +import org.springframework.util.CollectionUtils; |
| 30 | +import org.springframework.util.StringUtils; |
| 31 | + |
| 32 | +import java.util.HashMap; |
| 33 | +import java.util.List; |
| 34 | +import java.util.Map; |
| 35 | +import java.util.regex.Matcher; |
| 36 | +import java.util.regex.Pattern; |
| 37 | + |
| 38 | +/** |
| 39 | + * MCP Node: Node for calling MCP Server |
| 40 | + */ |
| 41 | +public class McpNode implements NodeAction { |
| 42 | + |
| 43 | + private static final Pattern VARIABLE_PATTERN = Pattern.compile("\\$\\{(.+?)\\}"); |
| 44 | + |
| 45 | + private static final Logger log = LoggerFactory.getLogger(McpNode.class); |
| 46 | + |
| 47 | + private final String url; |
| 48 | + |
| 49 | + private final String tool; |
| 50 | + |
| 51 | + private final Map<String, String> headers; |
| 52 | + |
| 53 | + private final Map<String, Object> params; |
| 54 | + |
| 55 | + private final String outputKey; |
| 56 | + |
| 57 | + private final List<String> inputParamKeys; |
| 58 | + |
| 59 | + private HttpClientSseClientTransport transport; |
| 60 | + |
| 61 | + private McpSyncClient client; |
| 62 | + |
| 63 | + private McpNode(Builder builder) { |
| 64 | + this.url = builder.url; |
| 65 | + this.tool = builder.tool; |
| 66 | + this.headers = builder.headers; |
| 67 | + this.params = builder.params; |
| 68 | + this.outputKey = builder.outputKey; |
| 69 | + this.inputParamKeys = builder.inputParamKeys; |
| 70 | + } |
| 71 | + |
| 72 | + @Override |
| 73 | + public Map<String, Object> apply(OverAllState state) throws Exception { |
| 74 | + log.info( |
| 75 | + "[McpNode] Start executing apply, original configuration: url={}, tool={}, headers={}, inputParamKeys={}", |
| 76 | + url, tool, headers, inputParamKeys); |
| 77 | + |
| 78 | + // Build transport and client |
| 79 | + HttpClientSseClientTransport.Builder transportBuilder = HttpClientSseClientTransport.builder(this.url); |
| 80 | + if (this.headers != null && !this.headers.isEmpty()) { |
| 81 | + transportBuilder.customizeRequest(req -> this.headers.forEach(req::header)); |
| 82 | + } |
| 83 | + this.transport = transportBuilder.build(); |
| 84 | + this.client = McpClient.sync(this.transport).build(); |
| 85 | + this.client.initialize(); |
| 86 | + // Variable replacement |
| 87 | + String finalTool = replaceVariables(tool, state); |
| 88 | + Map<String, Object> finalParams = new HashMap<>(); |
| 89 | + // 1. First read from inputParamKeys |
| 90 | + if (inputParamKeys != null) { |
| 91 | + for (String key : inputParamKeys) { |
| 92 | + Object value = state.value(key).orElse(null); |
| 93 | + if (value != null) { |
| 94 | + finalParams.put(key, value); |
| 95 | + } |
| 96 | + } |
| 97 | + } |
| 98 | + // 2. Then use params (after variable replacement) to overwrite |
| 99 | + Map<String, Object> replacedParams = replaceVariablesObj(params, state); |
| 100 | + if (replacedParams != null) { |
| 101 | + finalParams.putAll(replacedParams); |
| 102 | + } |
| 103 | + log.info("[McpNode] after replace params: url={}, tool={}, headers={}, params={}", url, finalTool, headers, |
| 104 | + finalParams); |
| 105 | + |
| 106 | + // Directly use the already initialized client |
| 107 | + CallToolResult result; |
| 108 | + try { |
| 109 | + McpSchema.CallToolRequest request = new McpSchema.CallToolRequest(finalTool, finalParams); |
| 110 | + log.info("[McpNode] CallToolRequest: {}", request); |
| 111 | + result = client.callTool(request); |
| 112 | + log.info("[McpNode] tool call result: {}", result); |
| 113 | + } |
| 114 | + catch (Exception e) { |
| 115 | + log.error("[McpNode] MCP call fail:", e); |
| 116 | + throw new McpNodeException("MCP call fail: " + e.getMessage(), e); |
| 117 | + } |
| 118 | + |
| 119 | + // Result handling |
| 120 | + Map<String, Object> updatedState = new HashMap<>(); |
| 121 | + // updatedState.put("mcp_result", result.content()); |
| 122 | + updatedState.put("messages", result.content()); |
| 123 | + if (StringUtils.hasLength(this.outputKey)) { |
| 124 | + Object content = result.content(); |
| 125 | + if (content instanceof List<?> list && !CollectionUtils.isEmpty(list)) { |
| 126 | + Object first = list.get(0); |
| 127 | + // Compatible with the text field of TextContent |
| 128 | + if (first instanceof TextContent textContent) { |
| 129 | + updatedState.put(this.outputKey, textContent.text()); |
| 130 | + } |
| 131 | + else if (first instanceof Map<?, ?> map && map.containsKey("text")) { |
| 132 | + updatedState.put(this.outputKey, map.get("text")); |
| 133 | + } |
| 134 | + else { |
| 135 | + updatedState.put(this.outputKey, first); |
| 136 | + } |
| 137 | + } |
| 138 | + else { |
| 139 | + updatedState.put(this.outputKey, content); |
| 140 | + } |
| 141 | + } |
| 142 | + log.info("[McpNode] update state: {}", updatedState); |
| 143 | + return updatedState; |
| 144 | + } |
| 145 | + |
| 146 | + private String replaceVariables(String template, OverAllState state) { |
| 147 | + if (template == null) |
| 148 | + return null; |
| 149 | + Matcher matcher = VARIABLE_PATTERN.matcher(template); |
| 150 | + StringBuilder result = new StringBuilder(); |
| 151 | + while (matcher.find()) { |
| 152 | + String key = matcher.group(1); |
| 153 | + Object value = state.value(key).orElse(""); |
| 154 | + log.info("[McpNode] replace param: {} -> {}", key, value); |
| 155 | + matcher.appendReplacement(result, value.toString()); |
| 156 | + } |
| 157 | + matcher.appendTail(result); |
| 158 | + return result.toString(); |
| 159 | + } |
| 160 | + |
| 161 | + private Map<String, Object> replaceVariablesObj(Map<String, Object> map, OverAllState state) { |
| 162 | + if (map == null) |
| 163 | + return null; |
| 164 | + Map<String, Object> result = new HashMap<>(); |
| 165 | + map.forEach((k, v) -> { |
| 166 | + if (v instanceof String) { |
| 167 | + result.put(k, replaceVariables((String) v, state)); |
| 168 | + } |
| 169 | + else { |
| 170 | + result.put(k, v); |
| 171 | + } |
| 172 | + }); |
| 173 | + return result; |
| 174 | + } |
| 175 | + |
| 176 | + public static Builder builder() { |
| 177 | + return new Builder(); |
| 178 | + } |
| 179 | + |
| 180 | + public static class Builder { |
| 181 | + |
| 182 | + private String url; |
| 183 | + |
| 184 | + private String tool; |
| 185 | + |
| 186 | + private Map<String, String> headers = new HashMap<>(); |
| 187 | + |
| 188 | + private Map<String, Object> params = new HashMap<>(); |
| 189 | + |
| 190 | + private String outputKey; |
| 191 | + |
| 192 | + private List<String> inputParamKeys; |
| 193 | + |
| 194 | + public Builder url(String url) { |
| 195 | + this.url = url; |
| 196 | + return this; |
| 197 | + } |
| 198 | + |
| 199 | + public Builder tool(String tool) { |
| 200 | + this.tool = tool; |
| 201 | + return this; |
| 202 | + } |
| 203 | + |
| 204 | + public Builder header(String name, String value) { |
| 205 | + this.headers.put(name, value); |
| 206 | + return this; |
| 207 | + } |
| 208 | + |
| 209 | + public Builder param(String name, Object value) { |
| 210 | + this.params.put(name, value); |
| 211 | + return this; |
| 212 | + } |
| 213 | + |
| 214 | + public Builder outputKey(String outputKey) { |
| 215 | + this.outputKey = outputKey; |
| 216 | + return this; |
| 217 | + } |
| 218 | + |
| 219 | + public Builder inputParamKeys(List<String> inputParamKeys) { |
| 220 | + this.inputParamKeys = inputParamKeys; |
| 221 | + return this; |
| 222 | + } |
| 223 | + |
| 224 | + public McpNode build() { |
| 225 | + return new McpNode(this); |
| 226 | + } |
| 227 | + |
| 228 | + } |
| 229 | + |
| 230 | + public static class McpNodeException extends RuntimeException { |
| 231 | + |
| 232 | + public McpNodeException(String message, Throwable cause) { |
| 233 | + super(message, cause); |
| 234 | + } |
| 235 | + |
| 236 | + } |
| 237 | + |
| 238 | +} |
0 commit comments