spring-ai-starter-mcp-client小试牛刀

本文主要研究下如何使用spring-ai-starter-mcp-client

步骤

pom.xml

		<dependency>
			<groupId>org.springframework.ai</groupId>
			<artifactId>spring-ai-starter-mcp-client</artifactId>
		</dependency>

		<dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-ollama-spring-boot-starter</artifactId>
        </dependency>

application.yml

spring:
  application:
    name: mcp-client-example
  main:
    web-application-type: none
  ai:
    ollama:
      base-url: http://localhost:11434
      chat:
        model: qwen2.5:latest
    mcp:
      client:
        enabled: true
        name: my-mcp-client
        version: 1.0.0
        request-timeout: 30s
        type: SYNC  # or ASYNC for reactive applications
        sse:
          connections:
            server1:
              url: http://localhost:8080
#            server2:
#              url: http://otherserver:8081
        toolcallback:
          enabled: 'true'
logging:
  level:
    io:
      modelcontextprotocol:
        client: WARN
        spec: WARN

示例

	@Bean
	public CommandLineRunner predefinedQuestions(ChatClient.Builder chatClientBuilder,
			ConfigurableApplicationContext context, SyncMcpToolCallbackProvider toolCallbackProvider) {

		return args -> {

			var chatClient = chatClientBuilder
					.defaultTools(toolCallbackProvider)
					.defaultAdvisors(new MessageChatMemoryAdvisor(new InMemoryChatMemory()))
					.build();

			System.out.println("\n>>> ASSISTANT: " + chatClient.prompt("帮我调用tool查一下xxx").call().content());
			System.out.println("\n>>> ASSISTANT: " + chatClient.prompt("取出create_time的最大值").call().content());

			context.close();
		};
	}

源码

McpClientAutoConfiguration

org/springframework/ai/mcp/client/autoconfigure/McpClientAutoConfiguration.java

@AutoConfiguration(after = { StdioTransportAutoConfiguration.class, SseHttpClientTransportAutoConfiguration.class,
		SseWebFluxTransportAutoConfiguration.class })
@ConditionalOnClass({ McpSchema.class })
@EnableConfigurationProperties(McpClientCommonProperties.class)
@ConditionalOnProperty(prefix = McpClientCommonProperties.CONFIG_PREFIX, name = "enabled", havingValue = "true",
		matchIfMissing = true)
public class McpClientAutoConfiguration {

	/**
	 * Create a dynamic client name based on the client name and the name of the server
	 * connection.
	 * @param clientName the client name as defined by the configuration
	 * @param serverConnectionName the name of the server connection being used by the
	 * client
	 * @return the connected client name
	 */
	private String connectedClientName(String clientName, String serverConnectionName) {
		return clientName + " - " + serverConnectionName;
	}

	/**
	 * Creates a list of {@link McpSyncClient} instances based on the available
	 * transports.
	 *
	 * <p>
	 * Each client is configured with:
	 * <ul>
	 * <li>Client information (name and version) from common properties
	 * <li>Request timeout settings
	 * <li>Custom configurations through {@link McpSyncClientConfigurer}
	 * </ul>
	 *
	 * <p>
	 * If initialization is enabled in properties, the clients are automatically
	 * initialized.
	 * @param mcpSyncClientConfigurer the configurer for customizing client creation
	 * @param commonProperties common MCP client properties
	 * @param transportsProvider provider of named MCP transports
	 * @return list of configured MCP sync clients
	 */
	@Bean
	@ConditionalOnProperty(prefix = McpClientCommonProperties.CONFIG_PREFIX, name = "type", havingValue = "SYNC",
			matchIfMissing = true)
	public List<McpSyncClient> mcpSyncClients(McpSyncClientConfigurer mcpSyncClientConfigurer,
			McpClientCommonProperties commonProperties,
			ObjectProvider<List<NamedClientMcpTransport>> transportsProvider) {

		List<McpSyncClient> mcpSyncClients = new ArrayList<>();

		List<NamedClientMcpTransport> namedTransports = transportsProvider.stream().flatMap(List::stream).toList();

		if (!CollectionUtils.isEmpty(namedTransports)) {
			for (NamedClientMcpTransport namedTransport : namedTransports) {

				McpSchema.Implementation clientInfo = new McpSchema.Implementation(
						this.connectedClientName(commonProperties.getName(), namedTransport.name()),
						commonProperties.getVersion());

				McpClient.SyncSpec syncSpec = McpClient.sync(namedTransport.transport())
					.clientInfo(clientInfo)
					.requestTimeout(commonProperties.getRequestTimeout());

				syncSpec = mcpSyncClientConfigurer.configure(namedTransport.name(), syncSpec);

				var syncClient = syncSpec.build();

				if (commonProperties.isInitialized()) {
					syncClient.initialize();
				}

				mcpSyncClients.add(syncClient);
			}
		}

		return mcpSyncClients;
	}

	//......
}	

McpClientAutoConfiguration依赖McpClientCommonProperties,它根据McpClientCommonProperties和List<NamedClientMcpTransport>构建List<McpSyncClient>List<McpAsyncClient>

McpToolCallbackAutoConfiguration

org/springframework/ai/mcp/client/autoconfigure/McpToolCallbackAutoConfiguration.java

@AutoConfiguration(after = { McpClientAutoConfiguration.class })
@EnableConfigurationProperties(McpClientCommonProperties.class)
@Conditional(McpToolCallbackAutoConfiguration.McpToolCallbackAutoconfigurationCondition.class)
public class McpToolCallbackAutoConfiguration {

	public static class McpToolCallbackAutoconfigurationCondition extends AllNestedConditions {

		public McpToolCallbackAutoconfigurationCondition() {
			super(ConfigurationPhase.PARSE_CONFIGURATION);
		}

		@ConditionalOnProperty(prefix = McpClientCommonProperties.CONFIG_PREFIX, name = "enabled", havingValue = "true",
				matchIfMissing = true)
		static class McpAutoConfigEnabled {

		}

		@ConditionalOnProperty(prefix = McpClientCommonProperties.CONFIG_PREFIX + ".toolcallback", name = "enabled",
				havingValue = "true", matchIfMissing = false)
		static class ToolCallbackProviderEnabled {

		}

	}

	/**
	 * Creates tool callbacks for all configured MCP clients.
	 *
	 * <p>
	 * These callbacks enable integration with Spring AI's tool execution framework,
	 * allowing MCP tools to be used as part of AI interactions.
	 * @param syncMcpClients provider of MCP sync clients
	 * @return list of tool callbacks for MCP integration
	 */
	@Bean
	@ConditionalOnProperty(prefix = McpClientCommonProperties.CONFIG_PREFIX, name = "type", havingValue = "SYNC",
			matchIfMissing = true)
	public ToolCallbackProvider mcpToolCallbacks(ObjectProvider<List<McpSyncClient>> syncMcpClients) {
		List<McpSyncClient> mcpClients = syncMcpClients.stream().flatMap(List::stream).toList();
		return new SyncMcpToolCallbackProvider(mcpClients);
	}

	@Bean
	@ConditionalOnProperty(prefix = McpClientCommonProperties.CONFIG_PREFIX, name = "type", havingValue = "ASYNC")
	public ToolCallbackProvider mcpAsyncToolCallbacks(ObjectProvider<List<McpAsyncClient>> mcpClientsProvider) {
		List<McpAsyncClient> mcpClients = mcpClientsProvider.stream().flatMap(List::stream).toList();
		return new AsyncMcpToolCallbackProvider(mcpClients);
	}

}

McpToolCallbackAutoConfiguration在spring.ai.mcp.client.enabledspring.ai.mcp.client.toolcallback.enabled都为true时才生效,它会根据List<McpSyncClient>去创建SyncMcpToolCallbackProvider或AsyncMcpToolCallbackProvider

小结

spring ai提供了spring-ai-starter-mcp-client用于快速集成mcpClient到chatClient中;McpClientAutoConfiguration依赖McpClientCommonProperties,它根据McpClientCommonProperties和List<NamedClientMcpTransport>构建List<McpSyncClient>List<McpAsyncClient>;McpToolCallbackAutoConfiguration在spring.ai.mcp.client.enabledspring.ai.mcp.client.toolcallback.enabled都为true时才生效,它会根据List<McpSyncClient>去创建SyncMcpToolCallbackProvider或AsyncMcpToolCallbackProvider

doc

<think>好的,用户问的是如何在多云平台(MCP)上集成Java和LangChain。首先,我需要明确用户的问题背景。LangChain是一个用于构建基于语言模型的应用程序的框架,通常与Python关联较多,而用户想用Java集成,这可能涉及到跨语言调用或者Java库的支持。另外,多云平台的环境需要考虑部署、服务发现、配置管理等问题。 首先,我应该确认LangChain是否有官方的Java支持。查阅资料发现,LangChain主要用Python开发,但可能有社区驱动的Java库或适配层。如果存在这样的库,集成步骤可能包括添加依赖、配置API密钥、编写链式逻辑等。如果不存在,可能需要通过REST API或gRPC与Python服务交互,这涉及到跨语言通信。 其次,多云平台的环境下,需要考虑如何部署Java应用和LangChain服务。可能需要容器化部署,使用Kubernetes进行编排,每个云平台上的集群需要统一的配置管理。此外,服务发现和负载均衡是关键,确保Java应用能够动态发现LangChain服务的实例。 然后,配置管理方面,需要将不同云平台的配置外部化,比如使用Spring Cloud Config或者Kubernetes ConfigMap。敏感信息如API密钥应通过Secrets管理,确保安全性。 接下来,分布式追踪和监控也是重要的一环。集成Jaeger或Zipkin来跟踪跨服务的请求,帮助排查问题。日志管理可能需要ELK栈或类似工具,确保日志集中存储和分析。 另外,用户可能需要处理多云平台的异构环境,比如不同云的存储服务。Java应用需要抽象这些差异,可能通过LangChain的模块化设计,或者使用多云存储解决方案如MinIO。 最后,需要考虑性能优化和容错机制,比如重试策略、熔断机制,使用Resilience4j等库来增强应用的健壮性。同时,自动化部署和CI/CD流程也是集成的一部分,确保代码在多云环境中顺利部署。 总结来说,集成步骤可能包括:环境准备、依赖管理、服务部署、配置管理、跨语言通信、监控追踪、多云适配和自动化部署。需要分步骤指导用户,并提醒可能的注意事项,比如Java与Python的交互延迟、版本兼容性等。</think>### Java与LangChain在多云平台(MCP)上的集成步骤 #### 1. **环境准备与依赖管理** - **LangChain服务部署**:若LangChain无原生Java SDK,需通过容器化部署Python服务并提供REST/gRPC接口。例如: ```python # LangChain服务端示例(Python) from fastapi import FastAPI from langchain.llms import OpenAI app = FastAPI() llm = OpenAI(api_key="YOUR_API_KEY") @app.post("/generate") def generate_text(prompt: str): return llm(prompt) ``` - **Java依赖配置**:通过Spring Boot或Quarkus框架集成HTTP客户端调用LangChain服务: ```xml <!-- Maven依赖示例 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> ``` #### 2. **多云平台适配** - **服务发现**:利用Kubernetes的Service对象或Istio实现跨云服务发现: ```yaml # Kubernetes Service示例 apiVersion: v1 kind: Service metadata: name: langchain-service spec: selector: app: langchain ports: - protocol: TCP port: 8080 targetPort: 8080 ``` - **配置管理**:使用Spring Cloud Config或HashiCorp Vault统一管理多环境配置: ```java // Java代码读取配置 @Value("${langchain.endpoint}") private String langchainEndpoint; ``` #### 3. **跨语言通信实现** - **HTTP调用示例**: ```java // Spring WebClient调用LangChain服务 public Mono<String> generateText(String prompt) { return WebClient.create() .post() .uri(langchainEndpoint + "/generate") .bodyValue(Map.of("prompt", prompt)) .retrieve() .bodyToMono(String.class); } ``` #### 4. **分布式追踪集成** - 集成Jaeger或Zipkin追踪跨云请求链路: ```java // Spring Cloud Sleuth + Zipkin配置 spring.zipkin.base-url=http://zipkin-server:9411 spring.sleuth.sampler.probability=1.0 ``` #### 5. **多云存储与数据处理** - 使用LangChain的文档加载模块适配多云存储(如AWS S3、Azure Blob): ```java // 伪代码示例:从S3加载文档 public String loadFromS3(String bucket, String key) { AmazonS3 s3Client = AmazonS3ClientBuilder.standard().build(); return s3Client.getObjectAsString(bucket, key); } ``` #### 6. **安全与治理** - **API密钥管理**:通过Kubernetes Secrets注入环境变量: ```yaml env: - name: LANGCHAIN_API_KEY valueFrom: secretKeyRef: name: langchain-secrets key: api-key ``` #### 7. **性能优化** - 添加缓存层(如Redis)减少对LangChain服务的重复调用: ```java @Cacheable("promptResponses") public String getCachedResponse(String prompt) { return generateText(prompt).block(); } ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值