|
| 1 | +/* |
| 2 | + * Copyright 2025-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 org.springframework.ai.autoconfigure.mcp.client; |
| 18 | + |
| 19 | +import java.util.ArrayList; |
| 20 | +import java.util.List; |
| 21 | + |
| 22 | +import io.modelcontextprotocol.client.McpAsyncClient; |
| 23 | +import io.modelcontextprotocol.client.McpClient; |
| 24 | +import io.modelcontextprotocol.client.McpSyncClient; |
| 25 | +import io.modelcontextprotocol.spec.McpSchema; |
| 26 | + |
| 27 | +import org.springframework.ai.mcp.McpToolUtils; |
| 28 | +import org.springframework.ai.mcp.customizer.McpAsyncClientCustomizer; |
| 29 | +import org.springframework.ai.mcp.customizer.McpSyncClientCustomizer; |
| 30 | +import org.springframework.ai.tool.ToolCallback; |
| 31 | +import org.springframework.beans.factory.ObjectProvider; |
| 32 | +import org.springframework.boot.autoconfigure.AutoConfiguration; |
| 33 | +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; |
| 34 | +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; |
| 35 | +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; |
| 36 | +import org.springframework.boot.context.properties.EnableConfigurationProperties; |
| 37 | +import org.springframework.context.annotation.Bean; |
| 38 | +import org.springframework.util.CollectionUtils; |
| 39 | + |
| 40 | +/** |
| 41 | + * Auto-configuration for Model Context Protocol (MCP) client support. |
| 42 | + * |
| 43 | + * <p> |
| 44 | + * This configuration class sets up the necessary beans for MCP client functionality, |
| 45 | + * including both synchronous and asynchronous clients along with their respective tool |
| 46 | + * callbacks. It is automatically enabled when the required classes are present on the |
| 47 | + * classpath and can be explicitly disabled through properties. |
| 48 | + * |
| 49 | + * <p> |
| 50 | + * Configuration Properties: |
| 51 | + * <ul> |
| 52 | + * <li>{@code spring.ai.mcp.client.enabled} - Enable/disable MCP client support (default: |
| 53 | + * true) |
| 54 | + * <li>{@code spring.ai.mcp.client.type} - Client type: SYNC or ASYNC (default: SYNC) |
| 55 | + * <li>{@code spring.ai.mcp.client.name} - Client implementation name |
| 56 | + * <li>{@code spring.ai.mcp.client.version} - Client implementation version |
| 57 | + * <li>{@code spring.ai.mcp.client.request-timeout} - Request timeout duration |
| 58 | + * <li>{@code spring.ai.mcp.client.initialized} - Whether to initialize clients on |
| 59 | + * creation |
| 60 | + * </ul> |
| 61 | + * |
| 62 | + * <p> |
| 63 | + * The configuration is activated after the transport-specific auto-configurations (Stdio, |
| 64 | + * SSE HTTP, and SSE WebFlux) to ensure proper initialization order. At least one |
| 65 | + * transport must be available for the clients to be created. |
| 66 | + * |
| 67 | + * <p> |
| 68 | + * Key features: |
| 69 | + * <ul> |
| 70 | + * <li>Synchronous and Asynchronous Client Support: |
| 71 | + * <ul> |
| 72 | + * <li>Creates and configures MCP clients based on available transports |
| 73 | + * <li>Supports both blocking (sync) and non-blocking (async) operations |
| 74 | + * <li>Automatic client initialization if enabled |
| 75 | + * </ul> |
| 76 | + * <li>Integration Support: |
| 77 | + * <ul> |
| 78 | + * <li>Sets up tool callbacks for Spring AI integration |
| 79 | + * <li>Supports multiple named transports |
| 80 | + * <li>Proper lifecycle management with automatic cleanup |
| 81 | + * </ul> |
| 82 | + * <li>Customization Options: |
| 83 | + * <ul> |
| 84 | + * <li>Extensible through {@link McpSyncClientCustomizer} and |
| 85 | + * {@link McpAsyncClientCustomizer} |
| 86 | + * <li>Configurable timeouts and client information |
| 87 | + * <li>Support for custom transport implementations |
| 88 | + * </ul> |
| 89 | + * </ul> |
| 90 | + * |
| 91 | + * @see McpSyncClient |
| 92 | + * @see McpAsyncClient |
| 93 | + * @see McpClientCommonProperties |
| 94 | + * @see McpSyncClientCustomizer |
| 95 | + * @see McpAsyncClientCustomizer |
| 96 | + * @see StdioTransportAutoConfiguration |
| 97 | + * @see SseHttpClientTransportAutoConfiguration |
| 98 | + * @see SseWebFluxTransportAutoConfiguration |
| 99 | + */ |
| 100 | +@AutoConfiguration(after = { StdioTransportAutoConfiguration.class, SseHttpClientTransportAutoConfiguration.class, |
| 101 | + SseWebFluxTransportAutoConfiguration.class }) |
| 102 | +@ConditionalOnClass({ McpSchema.class }) |
| 103 | +@EnableConfigurationProperties(McpClientCommonProperties.class) |
| 104 | +@ConditionalOnProperty(prefix = McpClientCommonProperties.CONFIG_PREFIX, name = "enabled", havingValue = "true", |
| 105 | + matchIfMissing = true) |
| 106 | +public class McpClientAutoConfiguration { |
| 107 | + |
| 108 | + /** |
| 109 | + * Creates a list of {@link McpSyncClient} instances based on the available |
| 110 | + * transports. |
| 111 | + * |
| 112 | + * <p> |
| 113 | + * Each client is configured with: |
| 114 | + * <ul> |
| 115 | + * <li>Client information (name and version) from common properties |
| 116 | + * <li>Request timeout settings |
| 117 | + * <li>Custom configurations through {@link McpSyncClientConfigurer} |
| 118 | + * </ul> |
| 119 | + * |
| 120 | + * <p> |
| 121 | + * If initialization is enabled in properties, the clients are automatically |
| 122 | + * initialized. |
| 123 | + * @param mcpSyncClientConfigurer the configurer for customizing client creation |
| 124 | + * @param commonProperties common MCP client properties |
| 125 | + * @param transportsProvider provider of named MCP transports |
| 126 | + * @return list of configured MCP sync clients |
| 127 | + */ |
| 128 | + @Bean |
| 129 | + @ConditionalOnProperty(prefix = McpClientCommonProperties.CONFIG_PREFIX, name = "type", havingValue = "SYNC", |
| 130 | + matchIfMissing = true) |
| 131 | + public List<McpSyncClient> mcpSyncClients(McpSyncClientConfigurer mcpSyncClientConfigurer, |
| 132 | + McpClientCommonProperties commonProperties, |
| 133 | + ObjectProvider<List<NamedClientMcpTransport>> transportsProvider) { |
| 134 | + |
| 135 | + List<McpSyncClient> mcpSyncClients = new ArrayList<>(); |
| 136 | + |
| 137 | + List<NamedClientMcpTransport> namedTransports = transportsProvider.stream().flatMap(List::stream).toList(); |
| 138 | + |
| 139 | + if (!CollectionUtils.isEmpty(namedTransports)) { |
| 140 | + for (NamedClientMcpTransport namedTransport : namedTransports) { |
| 141 | + |
| 142 | + McpSchema.Implementation clientInfo = new McpSchema.Implementation(commonProperties.getName(), |
| 143 | + commonProperties.getVersion()); |
| 144 | + |
| 145 | + McpClient.SyncSpec syncSpec = McpClient.sync(namedTransport.transport()) |
| 146 | + .clientInfo(clientInfo) |
| 147 | + .requestTimeout(commonProperties.getRequestTimeout()); |
| 148 | + |
| 149 | + syncSpec = mcpSyncClientConfigurer.configure(namedTransport.name(), syncSpec); |
| 150 | + |
| 151 | + var syncClient = syncSpec.build(); |
| 152 | + |
| 153 | + if (commonProperties.isInitialized()) { |
| 154 | + syncClient.initialize(); |
| 155 | + } |
| 156 | + |
| 157 | + mcpSyncClients.add(syncClient); |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + return mcpSyncClients; |
| 162 | + } |
| 163 | + |
| 164 | + /** |
| 165 | + * Creates tool callbacks for all configured MCP clients. |
| 166 | + * |
| 167 | + * <p> |
| 168 | + * These callbacks enable integration with Spring AI's tool execution framework, |
| 169 | + * allowing MCP tools to be used as part of AI interactions. |
| 170 | + * @param mcpClientsProvider provider of MCP sync clients |
| 171 | + * @return list of tool callbacks for MCP integration |
| 172 | + */ |
| 173 | + @Bean |
| 174 | + @ConditionalOnProperty(prefix = McpClientCommonProperties.CONFIG_PREFIX, name = "type", havingValue = "SYNC", |
| 175 | + matchIfMissing = true) |
| 176 | + public List<ToolCallback> toolCallbacks(ObjectProvider<List<McpSyncClient>> mcpClientsProvider) { |
| 177 | + List<McpSyncClient> mcpClients = mcpClientsProvider.stream().flatMap(List::stream).toList(); |
| 178 | + return McpToolUtils.getToolCallbacksFromSyncClients(mcpClients); |
| 179 | + } |
| 180 | + |
| 181 | + /** |
| 182 | + * Record class that implements {@link AutoCloseable} to ensure proper cleanup of MCP |
| 183 | + * clients. |
| 184 | + * |
| 185 | + * <p> |
| 186 | + * This class is responsible for closing all MCP sync clients when the application |
| 187 | + * context is closed, preventing resource leaks. |
| 188 | + */ |
| 189 | + public record ClosebleMcpSyncClients(List<McpSyncClient> clients) implements AutoCloseable { |
| 190 | + |
| 191 | + @Override |
| 192 | + public void close() { |
| 193 | + this.clients.forEach(McpSyncClient::close); |
| 194 | + } |
| 195 | + } |
| 196 | + |
| 197 | + /** |
| 198 | + * Creates a closeable wrapper for MCP sync clients to ensure proper resource cleanup. |
| 199 | + * @param clients the list of MCP sync clients to manage |
| 200 | + * @return a closeable wrapper for the clients |
| 201 | + */ |
| 202 | + @Bean |
| 203 | + @ConditionalOnProperty(prefix = McpClientCommonProperties.CONFIG_PREFIX, name = "type", havingValue = "SYNC", |
| 204 | + matchIfMissing = true) |
| 205 | + public ClosebleMcpSyncClients makeSyncClientsClosable(List<McpSyncClient> clients) { |
| 206 | + return new ClosebleMcpSyncClients(clients); |
| 207 | + } |
| 208 | + |
| 209 | + /** |
| 210 | + * Creates the default {@link McpSyncClientConfigurer} if none is provided. |
| 211 | + * |
| 212 | + * <p> |
| 213 | + * This configurer aggregates all available {@link McpSyncClientCustomizer} instances |
| 214 | + * to allow for customization of MCP sync client creation. |
| 215 | + * @param customizerProvider provider of MCP sync client customizers |
| 216 | + * @return the configured MCP sync client configurer |
| 217 | + */ |
| 218 | + @Bean |
| 219 | + @ConditionalOnMissingBean |
| 220 | + @ConditionalOnProperty(prefix = McpClientCommonProperties.CONFIG_PREFIX, name = "type", havingValue = "SYNC", |
| 221 | + matchIfMissing = true) |
| 222 | + McpSyncClientConfigurer mcpSyncClientConfigurer(ObjectProvider<McpSyncClientCustomizer> customizerProvider) { |
| 223 | + McpSyncClientConfigurer configurer = new McpSyncClientConfigurer(); |
| 224 | + configurer.setCustomizers(customizerProvider.orderedStream().toList()); |
| 225 | + return configurer; |
| 226 | + } |
| 227 | + |
| 228 | + // Async client configuration |
| 229 | + |
| 230 | + @Bean |
| 231 | + @ConditionalOnProperty(prefix = McpClientCommonProperties.CONFIG_PREFIX, name = "type", havingValue = "ASYNC") |
| 232 | + public List<McpAsyncClient> mcpAsyncClients(McpAsyncClientConfigurer mcpSyncClientConfigurer, |
| 233 | + McpClientCommonProperties commonProperties, |
| 234 | + ObjectProvider<List<NamedClientMcpTransport>> transportsProvider) { |
| 235 | + |
| 236 | + List<McpAsyncClient> mcpSyncClients = new ArrayList<>(); |
| 237 | + |
| 238 | + List<NamedClientMcpTransport> namedTransports = transportsProvider.stream().flatMap(List::stream).toList(); |
| 239 | + |
| 240 | + if (!CollectionUtils.isEmpty(namedTransports)) { |
| 241 | + for (NamedClientMcpTransport namedTransport : namedTransports) { |
| 242 | + |
| 243 | + McpSchema.Implementation clientInfo = new McpSchema.Implementation(commonProperties.getName(), |
| 244 | + commonProperties.getVersion()); |
| 245 | + |
| 246 | + McpClient.AsyncSpec syncSpec = McpClient.async(namedTransport.transport()) |
| 247 | + .clientInfo(clientInfo) |
| 248 | + .requestTimeout(commonProperties.getRequestTimeout()); |
| 249 | + |
| 250 | + syncSpec = mcpSyncClientConfigurer.configure(namedTransport.name(), syncSpec); |
| 251 | + |
| 252 | + var syncClient = syncSpec.build(); |
| 253 | + |
| 254 | + if (commonProperties.isInitialized()) { |
| 255 | + syncClient.initialize(); |
| 256 | + } |
| 257 | + |
| 258 | + mcpSyncClients.add(syncClient); |
| 259 | + } |
| 260 | + } |
| 261 | + |
| 262 | + return mcpSyncClients; |
| 263 | + } |
| 264 | + |
| 265 | + @Bean |
| 266 | + @ConditionalOnProperty(prefix = McpClientCommonProperties.CONFIG_PREFIX, name = "type", havingValue = "ASYNC") |
| 267 | + public List<ToolCallback> asyncToolCallbacks(ObjectProvider<List<McpAsyncClient>> mcpClientsProvider) { |
| 268 | + List<McpAsyncClient> mcpClients = mcpClientsProvider.stream().flatMap(List::stream).toList(); |
| 269 | + return McpToolUtils.getToolCallbacksFromAsyncClinents(mcpClients); |
| 270 | + } |
| 271 | + |
| 272 | + public record ClosebleMcpAsyncClients(List<McpAsyncClient> clients) implements AutoCloseable { |
| 273 | + @Override |
| 274 | + public void close() { |
| 275 | + this.clients.forEach(McpAsyncClient::close); |
| 276 | + } |
| 277 | + } |
| 278 | + |
| 279 | + @Bean |
| 280 | + @ConditionalOnProperty(prefix = McpClientCommonProperties.CONFIG_PREFIX, name = "type", havingValue = "ASYNC") |
| 281 | + public ClosebleMcpAsyncClients makeAsynClientsClosable(List<McpAsyncClient> clients) { |
| 282 | + return new ClosebleMcpAsyncClients(clients); |
| 283 | + } |
| 284 | + |
| 285 | + @Bean |
| 286 | + @ConditionalOnMissingBean |
| 287 | + @ConditionalOnProperty(prefix = McpClientCommonProperties.CONFIG_PREFIX, name = "type", havingValue = "ASYNC") |
| 288 | + McpAsyncClientConfigurer mcpAsyncClientConfigurer(ObjectProvider<McpAsyncClientCustomizer> customizerProvider) { |
| 289 | + McpAsyncClientConfigurer configurer = new McpAsyncClientConfigurer(); |
| 290 | + configurer.setCustomizers(customizerProvider.orderedStream().toList()); |
| 291 | + return configurer; |
| 292 | + } |
| 293 | + |
| 294 | +} |
0 commit comments